From: Kibum Kim Date: Mon, 9 Jan 2012 08:19:24 +0000 (+0900) Subject: Git Init X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=f7d6a7695dfc4f7c03732ece121fc9f4a8a5ad2f;p=profile%2Fivi%2Fwrt-plugins-tizen.git Git Init --- diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e6d02f4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,30 @@ +.cproject +.project +.settings +*.wgt +Debug +*.so +*.swp +CMakeCache.txt +CMakeFiles +build-stamp +cmake_install.cmake +configure-stamp +debian/debhelper.log +debian/files +debian/wrt-plugins-tizen-dbg.debhelper.log +debian/wrt-plugins-tizen-dbg.substvars +debian/wrt-plugins-tizen-dbg/ +debian/wrt-plugins-tizen.debhelper.log +debian/wrt-plugins-tizen.install +debian/wrt-plugins-tizen.postinst.debhelper +debian/wrt-plugins-tizen.postrm.debhelper +debian/wrt-plugins-tizen.substvars +debian/wrt-plugins-tizen/ +debian/substvars +debian/tmp/ +install_manifest.txt +Makefile +config.guess +config.sub + diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100755 index 0000000..d511be3 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,127 @@ +cmake_minimum_required(VERSION 2.6) + + +project(wrt-plugins-tizen) + + +################################################################################ +# Required platform modules + +include(FindPkgConfig) + +pkg_search_module(webkit REQUIRED ewebkit>=0.1.0) +pkg_search_module(dpl REQUIRED dpl-efl>=1.0.0) +pkg_search_module(wrt-plugin-api REQUIRED wrt-plugin-api>=1.1.1) +pkg_search_module(wrt-deviceapis-commons REQUIRED wrt-deviceapis-commons) +pkg_search_module(wrt-deviceapis-commons-javascript REQUIRED wrt-deviceapis-commons-javascript) + +include_directories( + ${webkit_INCLUDE_DIRS} + ${dpl_INCLUDE_DIRS} + ${wrt-plugin-api_INCLUDE_DIRS} + ${wrt-deviceapis-commons_INCLUDE_DIRS} + ${wrt-deviceapis-commons-javascript_INCLUDE_DIRS} +) + + +################################################################################ +# Build options + +# +# Logs +# + +OPTION(DPL_LOG "DPL logs status" ON) + +IF(DPL_LOG) + MESSAGE(STATUS "Logging enabled for DPL") + ADD_DEFINITIONS("-DDPL_LOGS_ENABLED") +ELSE(DPL_LOG) + MESSAGE(STATUS "Logging disabled for DPL") +ENDIF(DPL_LOG) + +############################################################################### +# Set build type (Release by default) +IF("${CMAKE_BUILD_TYPE}" STREQUAL "") + SET(CMAKE_BUILD_TYPE Release) +ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "") + +MESSAGE("Build type: ${CMAKE_BUILD_TYPE}") + +############################################################################## +# Compiler flags +SET(CMAKE_C_FLAGS_PROFILING "-O0 -g -pg") +SET(CMAKE_CXX_FLAGS_PROFILING "-O0 -std=c++0x -g -pg") +SET(CMAKE_C_FLAGS_DEBUG "-O0 -g") +SET(CMAKE_CXX_FLAGS_DEBUG "-O0 -std=c++0x -g") +SET(CMAKE_C_FLAGS_RELEASE "-O2 -g") +SET(CMAKE_CXX_FLAGS_RELEASE "-O2 -std=c++0x -g") +#### + +ADD_DEFINITIONS("-DEXPORT_API=") +ADD_DEFINITIONS("-Wall") +#ADD_DEFINITIONS("-Werror") +#ADD_DEFINITIONS("-Wextra") + +################################################################################ +# Miscellaneous variables + +set(CONFIG_FILE_NAME "config.cmake") +set(DIR_COMMONS ${CMAKE_SOURCE_DIR}/src/commons) +set(LIBS_COMMON + ${dpl_LDFLAGS} + ${webkit_LDFLAGS} + ${wrt-deviceapis-commons_LDFLAGS} + ${wrt-deviceapis-commons-javascript_LDFLAGS} + ) + + +################################################################################ +# Target platform + +if (NOT DEFINED PLATFORM) + set(PLATFORM "Tizen") +endif () + +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR}/src + ${CMAKE_CURRENT_SOURCE_DIR}/src/platform + ${CMAKE_CURRENT_SOURCE_DIR}/src/platform/${PLATFORM} + ${CMAKE_CURRENT_SOURCE_DIR}/src/standards +) + +################################################################################ +# Schema of plugin's configuration file + +set(COMMON_CONFIG_DTD ${CMAKE_CURRENT_SOURCE_DIR}/config.dtd) +set(COMMON_CONFIG_DTD_DST /usr/etc/tizen-apis) +INSTALL(FILES ${COMMON_CONFIG_DTD} DESTINATION ${COMMON_CONFIG_DTD_DST}) + + +################################################################################ +# Macros used for including plugins from AL. + +function(add_subdir NAME) + message(STATUS "Building: ${CMAKE_CURRENT_SOURCE_DIR}/${NAME}") + add_subdirectory(${NAME}) +endfunction() + + +################################################################################ +# Subdirectories + +add_subdirectory(src) + + +################################################################################ +# Cache + +set(PLATFORM "${PLATFORM}" CACHE STRING "Target platform" FORCE) +set(CMAKE_CONFIG_FILE_NAME "${CMAKE_CONFIG_FILE_NAME}" CACHE + STRING "CMake configuration file name." FORCE) + + +################################################################################ +# Summary + +message(STATUS "PLATFORM = ${PLATFORM}") diff --git a/LICENSE b/LICENSE new file mode 100755 index 0000000..bbe9d02 --- /dev/null +++ b/LICENSE @@ -0,0 +1,206 @@ +Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + diff --git a/clean.sh b/clean.sh new file mode 100755 index 0000000..06dff1f --- /dev/null +++ b/clean.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +echo Performing clean + +function clean { + rm -rf CMakeCache.txt + rm -rf CMakeFiles + rm -rf cmake_install.cmake + rm -rf Makefile + rm -rf install_manifest.txt + rm -rf *.so + + for i in `ls`; do + if [ -d $i ]; then + cd $i; + clean; + cd .. + fi + done + } + + clean + + + diff --git a/config.dtd b/config.dtd new file mode 100644 index 0000000..f1a1de4 --- /dev/null +++ b/config.dtd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 0000000..721c226 --- /dev/null +++ b/debian/changelog @@ -0,0 +1,85 @@ +wrt-plugins-tizen (0.1.2-10) unstable; urgency=low + + * Application, Contact bug fix. UnitTest update + * Git : slp/pkgs/w/wrt-plugins-tizen + * Tag : wrt-plugins-tizen_0.1.2-10 + + -- Sangtai Kim Thu, 05 Jan 2012 13:50:04 +0900 + +wrt-plugins-tizen (0.1.2-9) unstable; urgency=low + + * Calendar bug fix + * Git : slp/pkgs/w/wrt-plugins-tizen + * Tag : wrt-plugins-tizen_0.1.2-9 + + -- Sangtai Kim Thu, 29 Dec 2011 17:51:34 +0900 + +wrt-plugins-tizen (0.1.2-8) unstable; urgency=low + + * Canlendar, Application, NFC bug fix + * Git : slp/pkgs/w/wrt-plugins-tizen + * Tag : wrt-plugins-tizen_0.1.2-8 + + -- Sangtai Kim Wed, 28 Dec 2011 19:04:55 +0900 + +wrt-plugins-tizen (0.1.2-7) unstable; urgency=low + + * NFC, Messaging, Sensor, bug fix + * Git: pkgs/w/wrt-plugins-tizen + * Tag: wrt-plugins-tizen_0.1.2-7 + + + -- Sangtai Kim Tue, 27 Dec 2011 15:32:53 +0900 + +wrt-plugins-tizen (0.1.2-6) unstable; urgency=low + + * NFC, Sensor, Bluetooth bug fix + * Git: pkgs/w/wrt-plugins-tizen + * Tag: wrt-plugins-tizen_0.1.2-6 + + + -- Sangtai Kim Fri, 23 Dec 2011 12:21:01 +0900 + +wrt-plugins-tizen (0.1.2-5) unstable; urgency=low + + * NFC, Message, Bluetooth bug fix + * Git: pkgs/w/wrt-plugins-tizen + * Tag: wrt-plugins-tizen_0.1.2-5 + + + -- Sangtai Kim Thu, 22 Dec 2011 18:40:27 +0900 + +wrt-plugins-tizen (0.1.2-4) unstable; urgency=low + + * removed the modules which are not included in Tizen spec + * Git: pkgs/w/wrt-plugins-tizen + * Tag: wrt-plugins-tizen_0.1.2-4 + + + -- Sangtai Kim Wed, 21 Dec 2011 19:14:19 +0900 + +wrt-plugins-tizen (0.1.2-3) unstable; urgency=low + + * NFC, Messaging, Time bug fix + * Git: pkgs/w/wrt-plugins-tizen + * Tag: wrt-plugins-tizen_0.1.2-3 + + + -- Sangtai Kim Tue, 20 Dec 2011 18:00:23 +0900 + +wrt-plugins-tizen (0.1.2-1) unstable; urgency=low + + * Enable Sensor module + * Git: pkgs/w/wrt-plugins-tizen + * Tag: wrt-plugins-tizen_0.1.2-1 + + + -- Sangtai Kim Mon, 19 Dec 2011 16:27:02 +0900 + +wrt-plugins-tizen (0.1.2-0) unstable; urgency=low + + * Initial release. + * Git: pkgs/w/wrt-plugins-tizen + * Tag: wrt-plugins-tizen_0.1.2-0 + + -- Sangtai Kim Wed, 07 Dec 2011 13:30:57 +0900 diff --git a/debian/compat b/debian/compat new file mode 100755 index 0000000..7ed6ff8 --- /dev/null +++ b/debian/compat @@ -0,0 +1 @@ +5 diff --git a/debian/control b/debian/control new file mode 100755 index 0000000..b0f7db8 --- /dev/null +++ b/debian/control @@ -0,0 +1,18 @@ +Source: wrt-plugins-tizen +Section: devel +Priority: extra +Maintainer: Taehee Lee , Sangtai Kim , Jaehyun Park , KeeDuck Kim +Build-Depends: debhelper (>= 5), wrt-dev, wrt-commons-dev, libwebkit-engine-dev, capi-location-geocoder-dev, libmm-camcorder-dev, capi-network-bluetooth-dev, capi-appfw-app-manager-dev, capi-appfw-application-dev, libslp-calendar-dev, capi-system-sensor-dev, libappsvc-dev, email-service-dev, libslp-msg-service-dev (>=0.5.0), capi-telephony-call-dev, libicu-dev, libnetwork-dev, libslp-setting-dev, libdevman-dev, capi-social-call-log-dev, libdownload-agent-dev,libaccounts-svc-dev , libslp-tapi-dev, wrt-plugins-common-dev, capi-network-nfc-dev +Uploaders: Sangtai Kim + +Package: wrt-plugins-tizen +Architecture: any +Section: libs +Depends: ${shlibs:Depends}, ${misc:Depends}, wrt +Description: JavaScript plugins for WebRuntime + +Package: wrt-plugins-tizen-dbg +Architecture: any +Section: debug +Depends: ${shlibs:Depends}, ${misc:Depends} +Description: JavaScript plugins for WebRuntime - debug diff --git a/debian/rules b/debian/rules new file mode 100755 index 0000000..15d7a3b --- /dev/null +++ b/debian/rules @@ -0,0 +1,135 @@ +#!/usr/bin/make -f +# -*- makefile -*- +# Sample debian/rules that uses debhelper. +# This file was originally written by Joey Hess and Craig Small. +# As a special exception, when this file is copied by dh-make into a +# dh-make output file, you may use that output file without restriction. +# This special exception was added by Craig Small in version 0.37 of dh-make. + +# Uncomment this to turn on verbose mode. +#export DH_VERBOSE=1 + + +# These are used for cross-compiling and for saving the configure script +# from having to guess our platform (since we know it already) +DEB_HOST_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE) +DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE) + +CFLAGS ?= -Wall -g -fvisibility=hidden -fPIC +CXXFLAGS ?= -Wall -g -fPIC +PREFIX ?= /usr/lib/wrt-plugins +CONFIG_DTD ?= /usr/etc/tizen-apis +DATADIR ?= /opt + +ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS))) + CFLAGS += -O0 + CXXFLAGS += -O0 +else + CFLAGS += -O2 + CXXFLAGS += -O2 +endif + +ifeq (,$(findstring no,$(DPL_LOG))) + DPL_LOGS_STATUS = "ON" +else + DPL_LOGS_STATUS = "OFF" +endif + +LDFLAGS += -Wl,--rpath=$(PREFIX)/lib -Wl,--as-needed -Wl,--hash-style=both# -Wl,--version-script=$(CURDIR)/wrt-plugins.map + +ifdef DEVPKG + CMAKEFLAGS += -DDEVPKG="$(DEVPKG)" +endif + +configure: configure-stamp +configure-stamp: + dh_testdir + # Add here commands to configure the package. + CFLAGS="$(CFLAGS)" CXXFLAGS="$(CXXFLAGS)" LDFLAGS="$(LDFLAGS)" cmake . -DCMAKE_INSTALL_PREFIX=$(PREFIX) $(CMAKEFLAGS) -DDPL_LOG=$(DPL_LOGS_STATUS) -DCMAKE_BUILD_TYPE="$(BUILD_TYPE)" + touch configure-stamp + +build: build-stamp + +build-stamp: configure-stamp + dh_testdir + + # Add here commands to compile the package. + $(MAKE) -j9 -l2.0 + #docbook-to-man debian/ncurses.sgml > ncurses.1 + + for f in `find $(CURDIR)/debian/ -name "*.in"`; do \ + cat $$f > $${f%.in}; \ + sed -i -e "s#@PREFIX@#$(PREFIX)#g" $${f%.in}; \ + sed -i -e "s#@CONFIG_DTD@#$(CONFIG_DTD)#g" $${f%.in}; \ + sed -i -e "s#@DATADIR@#$(DATADIR)#g" $${f%.in}; \ + done + + touch $@ + +clean: + dh_testdir + dh_testroot + rm -f build-stamp configure-stamp +# -$(MAKE) distclean + ./clean.sh + +ifneq "$(wildcard /usr/share/misc/config.sub)" "" + cp -f /usr/share/misc/config.sub config.sub +endif +ifneq "$(wildcard /usr/share/misc/config.guess)" "" + cp -f /usr/share/misc/config.guess config.guess +endif + + for f in `find $(CURDIR)/debian/ -name "*.in"`; do \ + rm -f $${f%.in}; \ + done + + dh_clean + +install: build + dh_testdir + dh_testroot + dh_clean -k + dh_installdirs + + # Add here commands to install the package into debian/ncurses. + $(MAKE) DESTDIR=$(CURDIR)/debian/tmp install + + +# Build architecture-independent files here. +binary-indep: build install +# We have nothing to do by default. + +# Build architecture-dependent files here. +binary-arch: build install + dh_testdir + dh_testroot + dh_installchangelogs + dh_installdocs + dh_installexamples + dh_install --sourcedir=debian/tmp +# dh_installmenu +# dh_installdebconf +# dh_installlogrotate +# dh_installemacsen +# dh_installpam +# dh_installmime +# dh_python +# dh_installinit +# dh_installcron +# dh_installinfo + dh_installman + dh_link + dh_strip --dbg-package=wrt-plugins-tizen-dbg + dh_compress + dh_fixperms +# dh_perl + dh_makeshlibs + dh_installdeb + dh_shlibdeps + dh_gencontrol + dh_md5sums + dh_builddeb + +binary: binary-indep binary-arch +.PHONY: build clean binary-indep binary-arch binary install diff --git a/debian/wrt-plugins-tizen.install.in b/debian/wrt-plugins-tizen.install.in new file mode 100755 index 0000000..a0c4cc5 --- /dev/null +++ b/debian/wrt-plugins-tizen.install.in @@ -0,0 +1,2 @@ +@PREFIX@/* +@CONFIG_DTD@/* diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..2b23445 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,26 @@ +# Includes CMake configuration file (*.cmake), preserving appropriate paths. +macro(include_config_file INCLUDED_CONFIG_FILE_PATH) + get_filename_component(CURRENT_CONFIG_FILE_PATH ${CMAKE_CURRENT_LIST_FILE} PATH) + include(${CURRENT_CONFIG_FILE_PATH}/${INCLUDED_CONFIG_FILE_PATH}/${CONFIG_FILE_NAME} OPTIONAL) +endmacro() + +# Gets actual path for CMake configuration file (*.cmake). +# By default, if no argument is passed, current path will be set to variable +# named CURRENT_PATH. +# @param [Optional] Name of the variable to set with current path. +macro(get_current_path) + set(VARIABLE "CURRENT_PATH") + if (${ARGC} GREATER 0) + set(VARIABLE ${ARGV0}) + endif () + get_filename_component(${VARIABLE} ${CMAKE_CURRENT_LIST_FILE} PATH) +endmacro() + +set(HOST_ARCH $ENV{DEB_HOST_ARCH}) +if("${HOST_ARCH}" MATCHES "armel") + set(HOST_ARCH "armel") +endif() + +add_subdirectory(platform) +add_subdirectory(standards) + diff --git a/src/platform/API/Application/ApplicationEvent.cpp b/src/platform/API/Application/ApplicationEvent.cpp new file mode 100755 index 0000000..09286ea --- /dev/null +++ b/src/platform/API/Application/ApplicationEvent.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "ApplicationEvent.h" + +namespace TizenApis { +namespace Api { +namespace Application { +ApplicationEvent::ApplicationEvent() +{ +} + +ApplicationEvent::~ApplicationEvent() +{ +} + +std::string ApplicationEvent::getCode() const +{ + return m_code; +} +void ApplicationEvent::setCode(const std::string code) +{ + m_code = code; +} + +ApplicationInformationPtr ApplicationEvent::getApplicationInformation() const +{ + return m_appinfo; +} +void ApplicationEvent::setApplicationInformation(const ApplicationInformationPtr &appinfo) +{ + m_appinfo = appinfo; +} + +} +} +} + diff --git a/src/platform/API/Application/ApplicationEvent.h b/src/platform/API/Application/ApplicationEvent.h new file mode 100755 index 0000000..c76c69b --- /dev/null +++ b/src/platform/API/Application/ApplicationEvent.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_API_APPLICATION_EVENT_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_H_ + +#include +#include +#include +#include +#include "ApplicationInformation.h" + + +#define APPLICATON_EVENT_CODE_INSTALLED "INSTALLED" +#define APPLICATON_EVENT_CODE_UNINSTALLED "UNINSTALLED" +#define APPLICATON_EVENT_CODE_UPDATED "UPDATED" + + +namespace TizenApis { +namespace Api { +namespace Application { + +class ApplicationEvent; +typedef DPL::SharedPtr ApplicationEventPtr; + +class ApplicationEvent +{ + public: + ApplicationEvent(); + ~ApplicationEvent(); + + std::string getCode() const; + void setCode(const std::string code ); + + ApplicationInformationPtr getApplicationInformation() const; + void setApplicationInformation(const ApplicationInformationPtr &appinfo); + + private: + ApplicationInformationPtr m_appinfo; + std::string m_code; +}; + +} +} +} + +#endif diff --git a/src/platform/API/Application/ApplicationFactory.cpp b/src/platform/API/Application/ApplicationFactory.cpp new file mode 100755 index 0000000..6ae12fd --- /dev/null +++ b/src/platform/API/Application/ApplicationFactory.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include "ApplicationFactory.h" + + +namespace TizenApis { +namespace Api { +namespace Application { + +IApplicationPtr ApplicationFactory::createApplication() { + return IApplicationPtr(new Platform::Application::Application()); +} + +ApplicationFactory& ApplicationFactory::getInstance() { + static ApplicationFactory theInstance; + return theInstance; +} + +ApplicationFactory::ApplicationFactory() { +} + +} +} +} diff --git a/src/platform/API/Application/ApplicationFactory.h b/src/platform/API/Application/ApplicationFactory.h new file mode 100755 index 0000000..89b6084 --- /dev/null +++ b/src/platform/API/Application/ApplicationFactory.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_API_APPLICATION_FACTORY_H_ +#define TIZENAPIS_API_APPLICATION_FACTORY_H_ + +#include +#include "IApplication.h" + +namespace TizenApis { +namespace Api { +namespace Application { + +class ApplicationFactory: DPL::Noncopyable { +public: + IApplicationPtr createApplication(); + static ApplicationFactory& getInstance(); + +protected: + ApplicationFactory(); +}; + +} +} +} + +#endif diff --git a/src/platform/API/Application/ApplicationInformation.cpp b/src/platform/API/Application/ApplicationInformation.cpp new file mode 100755 index 0000000..9bfa9da --- /dev/null +++ b/src/platform/API/Application/ApplicationInformation.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ApplicationInformation.h" + +namespace TizenApis { +namespace Api { +namespace Application { +ApplicationInformation::ApplicationInformation() +{ +} + +ApplicationInformation::~ApplicationInformation() +{ +} + +std::string ApplicationInformation::getName() const +{ + return m_name; +} +void ApplicationInformation::setName(const std::string &name) +{ + m_name = name; +} + +std::string ApplicationInformation::getPackage() const +{ + return m_package; +} +void ApplicationInformation::setPackage(const std::string &package) +{ + m_package = package; +} + +std::string ApplicationInformation::getIconPath() const +{ + return m_iconPath; +} +void ApplicationInformation::setIconPath(const std::string &iconPath) +{ + m_iconPath = iconPath; +} + +std::string ApplicationInformation::getVersion() const +{ + return m_version; +} +void ApplicationInformation::setVersion(const std::string &version) +{ + m_version = version; +} + +} +} +} diff --git a/src/platform/API/Application/ApplicationInformation.h b/src/platform/API/Application/ApplicationInformation.h new file mode 100755 index 0000000..03b31e2 --- /dev/null +++ b/src/platform/API/Application/ApplicationInformation.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_APPLICATION_INFORMATION_H_ +#define TIZENAPIS_API_APPLICATION_INFORMATION_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Application { + +class ApplicationInformation; +typedef DPL::SharedPtr ApplicationInformationPtr; + +typedef std::vector ApplicationInformationArray; +typedef DPL::SharedPtr ApplicationInformationArrayPtr; + +class ApplicationInformation +{ + public: + ApplicationInformation(); + ~ApplicationInformation(); + + std::string getName() const; + void setName(const std::string &name); + std::string getPackage() const; + void setPackage(const std::string &package); + std::string getIconPath() const; + void setIconPath(const std::string &iconPath); + std::string getVersion() const; + void setVersion(const std::string &version); + + private: + std::string m_name; + std::string m_package; + std::string m_iconPath; + std::string m_version; +}; +} +} +} +#endif diff --git a/src/platform/API/Application/ApplicationServiceExtraData.cpp b/src/platform/API/Application/ApplicationServiceExtraData.cpp new file mode 100755 index 0000000..36879c5 --- /dev/null +++ b/src/platform/API/Application/ApplicationServiceExtraData.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ApplicationServiceExtraData.h" + +namespace TizenApis { +namespace Api { +namespace Application { +ApplicationServiceExtraData::ApplicationServiceExtraData() +{ + LogDebug("entered"); +} + +ApplicationServiceExtraData::~ApplicationServiceExtraData() +{ + //nothing to do in destructor + LogDebug("entered"); +} + +std::string ApplicationServiceExtraData::getKey() const +{ + return m_key; +} +void ApplicationServiceExtraData::setKey(const std::string &key) +{ + m_key = key; +} + +std::string ApplicationServiceExtraData::getValue() const +{ + return m_value; +} +void ApplicationServiceExtraData::setValue(const std::string &value) +{ + m_value = value; +} + +} +} +} diff --git a/src/platform/API/Application/ApplicationServiceExtraData.h b/src/platform/API/Application/ApplicationServiceExtraData.h new file mode 100755 index 0000000..14b4364 --- /dev/null +++ b/src/platform/API/Application/ApplicationServiceExtraData.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_APPLICATION_SERVICE_EXTRA_DATA_H_ +#define TIZENAPIS_API_APPLICATION_SERVICE_EXTRA_DATA_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Application { + +class ApplicationServiceExtraData; +typedef DPL::SharedPtr ApplicationServiceExtraDataPtr; + +typedef std::vector ApplicationServiceExtraDataArray; +typedef DPL::SharedPtr ApplicationServiceExtraDataArrayPtr; + +/* This object represents a single extra data for service request and reply */ +class ApplicationServiceExtraData +{ + public: + ApplicationServiceExtraData(); + ~ApplicationServiceExtraData(); + + std::string getKey() const; + void setKey(const std::string &key); + + std::string getValue() const; + void setValue(const std::string &value); + + private: + std::string m_key; + std::string m_value; +}; +} +} +} +#endif diff --git a/src/platform/API/Application/ApplicationServiceReply.cpp b/src/platform/API/Application/ApplicationServiceReply.cpp new file mode 100755 index 0000000..fbac74a --- /dev/null +++ b/src/platform/API/Application/ApplicationServiceReply.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * @file ApplicationServiceReply.cpp + * @author Youngkyeong Yun (yk.yun@samsung.com) + * @version 0.1 + */ + + +#include "ApplicationServiceReply.h" + +namespace TizenApis { +namespace Api { +namespace Application { +ApplicationServiceReply::ApplicationServiceReply() +{ + LogDebug("entered"); + m_extraDataArray = ApplicationServiceExtraDataArrayPtr(new ApplicationServiceExtraDataArray); +} + +ApplicationServiceReply::~ApplicationServiceReply() +{ + //nothing to do in destructor + LogDebug("entered"); +} + +bool ApplicationServiceReply::getIsSucceed() const +{ + return m_issucceed; +} +void ApplicationServiceReply::setIsSucceed(const bool success) +{ + m_issucceed = success; +} + +ApplicationServiceExtraDataArrayPtr ApplicationServiceReply::getExtraDataArray() const +{ + return m_extraDataArray; +} +void ApplicationServiceReply::setExtraDataArray(const ApplicationServiceExtraDataArrayPtr &extraDataArray) +{ + m_extraDataArray = extraDataArray; +} + +void ApplicationServiceReply::addExtraData(const ApplicationServiceExtraDataPtr &extraData) +{ + m_extraDataArray->push_back(extraData); +} + +} +} +} diff --git a/src/platform/API/Application/ApplicationServiceReply.h b/src/platform/API/Application/ApplicationServiceReply.h new file mode 100755 index 0000000..a1cf029 --- /dev/null +++ b/src/platform/API/Application/ApplicationServiceReply.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_APPLICATION_SERVICE_REPLY_H_ +#define TIZENAPIS_API_APPLICATION_SERVICE_REPLY_H_ + +#include +#include +#include "ApplicationServiceExtraData.h" + +namespace TizenApis { +namespace Api { +namespace Application { + +class ApplicationServiceReply; +typedef DPL::SharedPtr ApplicationServiceReplyPtr; + +/* This object represents a single extra data for service request and reply */ +class ApplicationServiceReply +{ +public: + ApplicationServiceReply(); + ~ApplicationServiceReply(); + + bool getIsSucceed() const; + void setIsSucceed(const bool success); + ApplicationServiceExtraDataArrayPtr getExtraDataArray() const; + void setExtraDataArray(const ApplicationServiceExtraDataArrayPtr &extraDataArray); + void addExtraData(const ApplicationServiceExtraDataPtr &extraData); + +private: + ApplicationServiceExtraDataArrayPtr m_extraDataArray; + bool m_issucceed; +}; +} +} +} +#endif diff --git a/src/platform/API/Application/ApplicationServiceRequest.cpp b/src/platform/API/Application/ApplicationServiceRequest.cpp new file mode 100755 index 0000000..d9038f4 --- /dev/null +++ b/src/platform/API/Application/ApplicationServiceRequest.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * @file ApplicationServiceRequest.cpp + * @author Youngkyeong Yun (yk.yun@samsung.com) + * @version 0.1 + */ + + +#include "ApplicationServiceRequest.h" + +namespace TizenApis { +namespace Api { +namespace Application { +ApplicationServiceRequest::ApplicationServiceRequest() : + m_service(NULL) +{ + LogDebug("entered"); + m_extraDataArray = ApplicationServiceExtraDataArrayPtr(new ApplicationServiceExtraDataArray); +} + +ApplicationServiceRequest::~ApplicationServiceRequest() +{ + //nothing to do in destructor + LogDebug("entered"); +} + +std::string ApplicationServiceRequest::getOperation() const +{ + return m_operation; +} +void ApplicationServiceRequest::setOperation(const std::string &operation) +{ + m_operation = operation; +} + +std::string ApplicationServiceRequest::getUri() const +{ + return m_uri; +} +void ApplicationServiceRequest::setUri(const std::string &uri) +{ + m_uri = uri; +} + +std::string ApplicationServiceRequest::getMime() const +{ + return m_mime; +} +void ApplicationServiceRequest::setMime(const std::string &mime) +{ + m_mime = mime; +} + +std::string ApplicationServiceRequest::getPackage() const +{ + return m_package; +} +void ApplicationServiceRequest::setPackage(const std::string &package) +{ + m_package = package; +} + +ApplicationServiceExtraDataArrayPtr ApplicationServiceRequest::getExtraDataArray() const +{ + return m_extraDataArray; +} +void ApplicationServiceRequest::setExtraDataArray(const ApplicationServiceExtraDataArrayPtr &extraDataArray) +{ + m_extraDataArray = extraDataArray; +} + +void ApplicationServiceRequest::addExtraData(const ApplicationServiceExtraDataPtr &extraData) +{ + m_extraDataArray->push_back(extraData); +} + +service_h ApplicationServiceRequest::getService_h() const +{ + return m_service; +} +void ApplicationServiceRequest::setService_h(const service_h service) +{ + m_service = service; +} + +} +} +} diff --git a/src/platform/API/Application/ApplicationServiceRequest.h b/src/platform/API/Application/ApplicationServiceRequest.h new file mode 100755 index 0000000..10e6eaa --- /dev/null +++ b/src/platform/API/Application/ApplicationServiceRequest.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_APPLICATION_SERVICE_H_ +#define TIZENAPIS_API_APPLICATION_SERVICE_H_ + +#include +#include +#include +#include +#include +#include "ApplicationServiceExtraData.h" + +namespace TizenApis { +namespace Api { +namespace Application { + +class ApplicationServiceRequest; +typedef DPL::SharedPtr ApplicationServiceRequestPtr; + +/* This object represents a single extra data for service request and reply */ +class ApplicationServiceRequest +{ + public: + ApplicationServiceRequest(); + ~ApplicationServiceRequest(); + + std::string getOperation() const; + void setOperation(const std::string &operation); + + std::string getUri() const; + void setUri(const std::string &uri); + + std::string getMime() const; + void setMime(const std::string &uri); + + std::string getPackage() const; + void setPackage(const std::string &uri); + + ApplicationServiceExtraDataArrayPtr getExtraDataArray() const; + void setExtraDataArray(const ApplicationServiceExtraDataArrayPtr &extraDataArray); + void addExtraData(const ApplicationServiceExtraDataPtr &extraData); + + service_h getService_h() const; + void setService_h(const service_h service); + + + private: + std::string m_operation; + std::string m_uri; + std::string m_mime; + std::string m_package; + ApplicationServiceExtraDataArrayPtr m_extraDataArray; + service_h m_service; +}; +} +} +} +#endif diff --git a/src/platform/API/Application/EventGetApplication.h b/src/platform/API/Application/EventGetApplication.h new file mode 100755 index 0000000..ce631a6 --- /dev/null +++ b/src/platform/API/Application/EventGetApplication.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_EVENT_GET_APPLICATION_H_ +#define TIZENAPIS_API_EVENT_GET_APPLICATION_H_ + +#include +#include +#include "ApplicationInformation.h" + +namespace TizenApis { +namespace Api { +namespace Application { + +class EventGetApplication: public WrtDeviceApis::Commons::IEvent { +private: + ApplicationInformationPtr m_appinfo; + std::string m_package; + +public: + void setApplicationInformation(const ApplicationInformationPtr appinfo) + { + m_appinfo = appinfo; + } + + ApplicationInformationPtr getApplicationInformation() const + { + return m_appinfo; + } + + void setPackage(std::string package) + { + m_package = package; + } + + std::string getPackage() const + { + return m_package; + } + + EventGetApplication() + { + } +}; + +typedef DPL::SharedPtr EventGetApplicationPtr; + +} // Application +} // Api +} // TizenApis + +#endif \ No newline at end of file diff --git a/src/platform/API/Application/EventInstalledApplicationChanged.h b/src/platform/API/Application/EventInstalledApplicationChanged.h new file mode 100755 index 0000000..2f7f2c8 --- /dev/null +++ b/src/platform/API/Application/EventInstalledApplicationChanged.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_EVENT_INSTALLED_APPLICATION_CHANGED_H_ +#define TIZENAPIS_API_EVENT_INSTALLED_APPLICATION_CHANGED_H_ + +#include +#include +#include +#include +#include "ApplicationInformation.h" +#include "ApplicationEvent.h" + +namespace TizenApis { +namespace Api { +namespace Application { + +class EventInstalledApplicationChanged: public WrtDeviceApis::Commons::ListenerEvent +{ +private: + ApplicationInformationPtr m_appinfo; + std::string m_eventCode; +public: + + void setApplicationInformation(const ApplicationInformationPtr &appinfo) + { + m_appinfo = appinfo; + } + + ApplicationInformationPtr getApplicationInformation() const + { + return m_appinfo; + } + + void setEventCode(std::string code) + { + m_eventCode = code; + } + + std::string getEventCode() const + { + return m_eventCode; + } + + EventInstalledApplicationChanged() + { + } +}; + +typedef DPL::SharedPtr EventInstalledApplicationChangedPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter EventInstalledApplicationChangedEmitter; +typedef DPL::SharedPtr EventInstalledApplicationChangedEmitterPtr; + +} // Application +} // Api +} // TizenApis + +#endif \ No newline at end of file diff --git a/src/platform/API/Application/EventLaunchService.h b/src/platform/API/Application/EventLaunchService.h new file mode 100755 index 0000000..57375a8 --- /dev/null +++ b/src/platform/API/Application/EventLaunchService.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_EVENT_LAUNCH_SERVICE_H_ +#define TIZENAPIS_API_EVENT_LAUNCH_SERVICE_H_ + + + +#include +#include +#include "ApplicationServiceRequest.h" +#include "ApplicationServiceReply.h" +#include "ApplicationServiceExtraData.h" + +namespace TizenApis { +namespace Api { +namespace Application { + +class EventLaunchService: public WrtDeviceApis::Commons::IEvent { + +private: + ApplicationServiceRequestPtr m_request; + ApplicationServiceReplyPtr m_reply; + int callbackType; + +public: + /* EVENT TYPE */ + static const int APPLICATION_SERVICE_UNKNOWN = 0; + static const int APPLICATION_SERVICE_CALLBACK = 1; + static const int APPLICATION_SERVICE_REPLY_SUCCESS_CALLBACK = 2; + static const int APPLICATION_SERVICE_REPLY_FAIL_CALLBACK = 3; + static const int APPLICATION_SERVICE_REPLY_CANCEL_CALLBACK = 4; +public: + void addExtraDataToReply(std::string &key, std::string &value){ + + ApplicationServiceExtraDataPtr extraData(new ApplicationServiceExtraData()); + extraData->setKey(key); + extraData->setValue(value); + if( !m_reply ) + { + ApplicationServiceReplyPtr reply(new ApplicationServiceReply()); + + ApplicationServiceExtraDataArrayPtr extraDataArray(new ApplicationServiceExtraDataArray()); + reply->setExtraDataArray(extraDataArray); + setServiceReply(reply); + } + m_reply->addExtraData(extraData); + } + + + void setServiceRequest(ApplicationServiceRequestPtr &appservice){ + m_request = appservice; + } + + ApplicationServiceRequestPtr getServiceRequest() const{ + return m_request; + } + + void setServiceReply(ApplicationServiceReplyPtr &serviceReply){ + m_reply = serviceReply; + } + ApplicationServiceReplyPtr getServiceReply() const{ + return m_reply; + } + void setCallbackType(int callbacktype){ + callbackType = callbacktype; + } + int getCallbackType() const{ + return callbackType; + } + EventLaunchService() + { + } +}; + +typedef DPL::SharedPtr EventLaunchServicePtr; + +} // Application +} // Api +} // TizenApis + +#endif diff --git a/src/platform/API/Application/EventListInstalledApplications.h b/src/platform/API/Application/EventListInstalledApplications.h new file mode 100755 index 0000000..b9f1ec4 --- /dev/null +++ b/src/platform/API/Application/EventListInstalledApplications.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_EVENT_LIST_INSTALLED_APPLICATIONS_H_ +#define TIZENAPIS_API_EVENT_LIST_INSTALLED_APPLICATIONS_H_ + +#include +#include +#include "ApplicationInformation.h" + +namespace TizenApis { +namespace Api { +namespace Application { + +class EventListInstalledApplications: public WrtDeviceApis::Commons::IEvent { +private: + ApplicationInformationArrayPtr m_appinfoArray; + int m_eventType; +public: + static const int APPMANAGER_UNKNOWN = 0; + static const int APPMANAGER_LIST_INSTALLED_APPLICATIONS = 1; + static const int APPMANAGER_LIST_RUNNING_APPLICATIONS = 2; + +public: + void addApplicationInformation(const ApplicationInformationPtr appinfo) + { + if( !m_appinfoArray ) + { + ApplicationInformationArrayPtr appinfos(new ApplicationInformationArray()); + setApplicationInformationArray(appinfos); + } + m_appinfoArray->push_back(appinfo); + } + + const ApplicationInformationArrayPtr getApplicationInformationArray() const + { + return m_appinfoArray; + } + + void setApplicationInformationArray(ApplicationInformationArrayPtr appinfoArray){ + m_appinfoArray = appinfoArray; + } + + void setEventType(int type){ + m_eventType = type; + } + + int getEventType(){ + return m_eventType; + } + + EventListInstalledApplications() + { + } +}; + +typedef DPL::SharedPtr EventListInstalledApplicationsPtr; + +} // Application +} // Api +} // TizenApis + +#endif \ No newline at end of file diff --git a/src/platform/API/Application/IApplication.cpp b/src/platform/API/Application/IApplication.cpp new file mode 100755 index 0000000..32d6eec --- /dev/null +++ b/src/platform/API/Application/IApplication.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "IApplication.h" +namespace TizenApis { +namespace Api { +namespace Application{ + +using namespace WrtDeviceApis::Commons; + +IApplication::IApplication() : + EventRequestReceiver(ThreadEnum::APPLICATION_THREAD), + EventRequestReceiver(ThreadEnum::APPLICATION_THREAD), + EventRequestReceiver(ThreadEnum::APPLICATION_THREAD) +{ +} + +IApplication::~IApplication() +{ +} + +} +} +} diff --git a/src/platform/API/Application/IApplication.h b/src/platform/API/Application/IApplication.h new file mode 100755 index 0000000..0a155f7 --- /dev/null +++ b/src/platform/API/Application/IApplication.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_IAPPLICATION_H_ +#define TIZENAPIS_API_IAPPLICATION_H_ + +#include +#include +#include "EventListInstalledApplications.h" +#include "EventGetApplication.h" +#include "EventInstalledApplicationChanged.h" +#include "EventLaunchService.h" + +namespace TizenApis { +namespace Api { +namespace Application { + +class EventListInstalledApplications; +class EventGetApplication; +class EventLaunchService; + +class IApplication: public WrtDeviceApis::Commons::EventRequestReceiver, + public WrtDeviceApis::Commons::EventRequestReceiver, + public WrtDeviceApis::Commons::EventRequestReceiver +{ +public: + virtual ~IApplication(); + virtual void listApplications(const EventListInstalledApplicationsPtr& event) = 0; + virtual void getApplicationInformation(const EventGetApplicationPtr& event) = 0; + virtual long addApplicationListChangeListener(const EventInstalledApplicationChangedEmitterPtr& emitter) = 0; + virtual void removeApplicationListChangeListener(const EventInstalledApplicationChangedEmitter::IdType id) = 0; + virtual void launchService(const EventLaunchServicePtr& event) = 0; + + protected: + IApplication(); + + virtual void OnRequestReceived(const EventListInstalledApplicationsPtr& event) = 0; + virtual void OnRequestReceived(const EventGetApplicationPtr& event) = 0; + virtual void OnRequestReceived(const EventLaunchServicePtr& event) = 0; + + }; + +typedef DPL::SharedPtr IApplicationPtr; + +} +} +} + +#endif diff --git a/src/platform/API/Application/config.cmake b/src/platform/API/Application/config.cmake new file mode 100755 index 0000000..ab2158f --- /dev/null +++ b/src/platform/API/Application/config.cmake @@ -0,0 +1,11 @@ +get_current_path() +set(SRCS_PLATFORM_API_APPLICATION + ${CURRENT_PATH}/ApplicationFactory.cpp + ${CURRENT_PATH}/IApplication.cpp + ${CURRENT_PATH}/ApplicationInformation.cpp + ${CURRENT_PATH}/ApplicationEvent.cpp + ${CURRENT_PATH}/ApplicationServiceExtraData.cpp + ${CURRENT_PATH}/ApplicationServiceRequest.cpp + ${CURRENT_PATH}/ApplicationServiceReply.cpp + PARENT_SCOPE +) diff --git a/src/platform/API/Bluetooth/BTDevice.h b/src/platform/API/Bluetooth/BTDevice.h new file mode 100644 index 0000000..92e97fa --- /dev/null +++ b/src/platform/API/Bluetooth/BTDevice.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_BT_DEVICE_H_ +#define TIZENAPIS_API_BT_DEVICE_H_ + +#include +#include + +namespace TizenApis { +namespace Api { +namespace Bluetooth { +struct BluetoothDeviceDataClass +{ + unsigned short major; + unsigned short minor; + int majorServiceMask; +}; + +class BluetoothDeviceData +{ +public: + std::string name; + std::string address; + BluetoothDeviceDataClass btClass; + bool isBonded; + bool isTrusted; + bool isConnected; + std::vector uuids; + + BluetoothDeviceData() {}; + ~BluetoothDeviceData() {}; +}; + +typedef DPL::SharedPtr BluetoothDeviceDataPtr; + +struct BluetoothSocketData +{ + std::string uuid; + bool isServer; + unsigned short int protocol; + unsigned short int state; + int connectedSocket; + int registeredSocket; + BluetoothDeviceData peerDevice; +}; +} +} +} + +#endif diff --git a/src/platform/API/Bluetooth/BluetoothFactory.cpp b/src/platform/API/Bluetooth/BluetoothFactory.cpp new file mode 100755 index 0000000..5e868b5 --- /dev/null +++ b/src/platform/API/Bluetooth/BluetoothFactory.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#include +#include +#include +#include "BluetoothFactory.h" + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + + +IBluetoothAdapterManagerPtr BluetoothFactory::getBluetoothAdapterManager() +{ + return IBluetoothAdapterManagerPtr( new Platform::Bluetooth::BluetoothAdapterManager() ); +} + +IBluetoothDeviceManagerPtr BluetoothFactory::getBluetoothDeviceManager() +{ + return IBluetoothDeviceManagerPtr( new Platform::Bluetooth::BluetoothDeviceManager() ); +} + +IBluetoothSocketManagerPtr BluetoothFactory::getBluetoothSocketManager() +{ + return IBluetoothSocketManagerPtr( new Platform::Bluetooth::BluetoothSocketManager() ); +} + + +BluetoothFactory& BluetoothFactory::getInstance() +{ + static BluetoothFactory theInstance; + return theInstance; +} + +BluetoothFactory::BluetoothFactory() +{ +} + +BluetoothFactory::~BluetoothFactory() +{ +} +} +} +} diff --git a/src/platform/API/Bluetooth/BluetoothFactory.h b/src/platform/API/Bluetooth/BluetoothFactory.h new file mode 100755 index 0000000..511cb3c --- /dev/null +++ b/src/platform/API/Bluetooth/BluetoothFactory.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef TIZENAPIS_API_BLUETOOTH_FACTORY_H_ +#define TIZENAPIS_API_BLUETOOTH_FACTORY_H_ + +#include +#include "IBluetoothAdapterManager.h" +#include "IBluetoothDeviceManager.h" +#include "IBluetoothSocketManager.h" + + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +class BluetoothFactory : DPL::Noncopyable +{ +public: + IBluetoothAdapterManagerPtr getBluetoothAdapterManager(); + IBluetoothDeviceManagerPtr getBluetoothDeviceManager(); + IBluetoothSocketManagerPtr getBluetoothSocketManager(); + static BluetoothFactory& getInstance(); + +protected: + BluetoothFactory(); + ~BluetoothFactory(); +}; + +} +} +} + +#endif + diff --git a/src/platform/API/Bluetooth/BluetoothProperty.h b/src/platform/API/Bluetooth/BluetoothProperty.h new file mode 100644 index 0000000..1dc9ada --- /dev/null +++ b/src/platform/API/Bluetooth/BluetoothProperty.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_BLUETOOTH_PROPERTY_H_ +#define TIZENAPIS_API_BLUETOOTH_PROPERTY_H_ + +#define SOCKET_STATE_CLOSED "SOCKET_STATE_CLOSED" +#define SOCKET_STATE_OPEN "SOCKET_STATE_OPEN" +#define PROTOCOL_TYPE_RFCOMM "PROTOCOL_TYPE_RFCOMM" +#define PROTOCOL_TYPE_L2CAP "PROTOCOL_TYPE_L2CAP" +#define SECURITY_LEVEL_LOW "SECURITY_LEVEL_LOW" +#define SECURITY_LEVEL_MEDIUM "SECURITY_LEVEL_MEDIUM" +#define SECURITY_LEVEL_HIGH "SECURITY_LEVEL_HIGH" + + +#define SOCKET_STATE_CLOSED_VALUE "CLOSED" +#define SOCKET_STATE_OPEN_VALUE "OPEN" +#define SOCKET_STATE_CLOSED_VALUE_INT 0 +#define SOCKET_STATE_OPEN_VALUE_INT 1 + +#define PROTOCOL_TYPE_RFCOMM_VALUE "RFCOMM" +#define PROTOCOL_TYPE_L2CAP_VALUE "L2CAP" +#define SECURITY_LEVEL_LOW_VALUE "LOW" +#define SECURITY_LEVEL_MEDIUM_VALUE "MEDIUM" +#define SECURITY_LEVEL_HIGH_VALUE "HIGH" +#define PROTOCOL_TYPE_RFCOMM_VALUE_INT 0 +#define PROTOCOL_TYPE_L2CAP_VALUE_INT 1 +#define SECURITY_LEVEL_LOW_VALUE_INT 0 +#define SECURITY_LEVEL_MEDIUM_VALUE_INT 1 +#define SECURITY_LEVEL_HIGH_VALUE_INT 2 +#define UUID_STR_LENGTH 36 + +#endif + diff --git a/src/platform/API/Bluetooth/EventBTConnectToServiceByUUID.h b/src/platform/API/Bluetooth/EventBTConnectToServiceByUUID.h new file mode 100755 index 0000000..a9c4130 --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTConnectToServiceByUUID.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_API_BLUETOOTH_CONNECTED_TO_SERVICE_BY_UUID_H_ +#define TIZENAPIS_API_BLUETOOTH_CONNECTED_TO_SERVICE_BY_UUID_H_ + +#include +#include +#include "BTDevice.h" + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +class EventBTConnectToServiceByUUID : public WrtDeviceApis::Commons::IEvent +{ +private : + BluetoothSocketData m_socketData; + bool m_result; +public: + EventBTConnectToServiceByUUID() { LogDebug("entered"); } + ~EventBTConnectToServiceByUUID() { } + void setSocketData(BluetoothSocketData socketData) { m_socketData = socketData;} + BluetoothSocketData getSocketData() { return m_socketData;} +}; + +typedef DPL::SharedPtr EventBTConnectToServiceByUUIDPtr; +} +} +} + +#endif diff --git a/src/platform/API/Bluetooth/EventBTCreateDestroyBonding.h b/src/platform/API/Bluetooth/EventBTCreateDestroyBonding.h new file mode 100755 index 0000000..b980292 --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTCreateDestroyBonding.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_BLUETOOTH_CREATE_DESTROY_BONDING_H_ +#define TIZENAPIS_API_BLUETOOTH_CREATE_DESTROY_BONDING_H_ + + +#include +#include +#include "BTDevice.h" + + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +class EventBTCreateDestroyBonding : public WrtDeviceApis::Commons::IEvent +{ +private: + std::string m_address; + bool m_operation; + BluetoothDeviceData m_device; +public: + EventBTCreateDestroyBonding() { LogDebug("entered"); } + ~EventBTCreateDestroyBonding() { } + void setAddress(std::string address) { m_address = address;} + std::string getAddress() { return m_address;} + void setCreateBonding(void) { m_operation = true; } + void setDestroyBonding(void) { m_operation = false; } + bool isCreateBonding(void) { return m_operation == true;} + bool isDestroyBonding(void) { return m_operation == true;} + BluetoothDeviceData getDevice() { return m_device;} + void setDevice(BluetoothDeviceData device) { m_device = device;} +}; + +typedef DPL::SharedPtr EventBTCreateDestroyBondingPtr; +} +} +} + +#endif diff --git a/src/platform/API/Bluetooth/EventBTGetAdapter.h b/src/platform/API/Bluetooth/EventBTGetAdapter.h new file mode 100755 index 0000000..9b95c78 --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTGetAdapter.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_BLUETOOTH_BT_GET_ADAPTER_H_ +#define TIZENAPIS_API_BLUETOOTH_BT_GET_ADAPTER_H_ + +#include +#include + + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +class EventBTGetAdapter : public WrtDeviceApis::Commons::IEvent +{ +private: + bool m_result; +public: + EventBTGetAdapter() { m_result = false;} + ~EventBTGetAdapter() { } + +}; +typedef DPL::SharedPtr EventBTGetAdapterPtr; +} +} +} + +#endif diff --git a/src/platform/API/Bluetooth/EventBTGetDevice.cpp b/src/platform/API/Bluetooth/EventBTGetDevice.cpp new file mode 100755 index 0000000..5dd856e --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTGetDevice.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "EventBTGetDevice.h" + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + + +void EventBTGetDevice::setDevice(BluetoothDeviceData device) +{ + m_Device = device; +} + +void EventBTGetDevice::setAddress(std::string address) +{ + m_address = address; +} + +std::string EventBTGetDevice::getAddress() +{ + return m_address; +} + + +BluetoothDeviceData EventBTGetDevice::getDevice() +{ + return m_Device; +} + +} +} +} diff --git a/src/platform/API/Bluetooth/EventBTGetDevice.h b/src/platform/API/Bluetooth/EventBTGetDevice.h new file mode 100755 index 0000000..cb7c59e --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTGetDevice.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + #ifndef TIZENAPIS_API_BLUETOOTH_GET_DEVICE_H_ +#define TIZENAPIS_API_BLUETOOTH_GET_DEVICE_H_ + +#include +#include +#include "BTDevice.h" + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + + +class EventBTGetDevice : public WrtDeviceApis::Commons::IEvent +{ +private: + BluetoothDeviceData m_Device; + std::string m_address; +public: + EventBTGetDevice() { LogDebug("entered"); } + ~EventBTGetDevice() { } + + void setDevice(BluetoothDeviceData device); + void setAddress(std::string address) ; + std::string getAddress() ; + BluetoothDeviceData getDevice(); + + +}; + +typedef DPL::SharedPtr EventBTGetDevicePtr; +} +} +} +#endif diff --git a/src/platform/API/Bluetooth/EventBTGetKnownDevices.cpp b/src/platform/API/Bluetooth/EventBTGetKnownDevices.cpp new file mode 100755 index 0000000..c89cd84 --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTGetKnownDevices.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "EventBTGetKnownDevices.h" + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +void EventBTGetKnownDevices::addDevice(BluetoothDeviceData device) +{ + m_Devices.push_back(device); +} + +std::vector EventBTGetKnownDevices::getDevices() +{ + return m_Devices; +} + +} +} +} diff --git a/src/platform/API/Bluetooth/EventBTGetKnownDevices.h b/src/platform/API/Bluetooth/EventBTGetKnownDevices.h new file mode 100755 index 0000000..4894249 --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTGetKnownDevices.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_BLUETOOTH_GET_KNOWN_DEVICES_H_ +#define TIZENAPIS_API_BLUETOOTH_GET_KNOWN_DEVICES_H_ + +#include +#include +#include "BTDevice.h" + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + + +class EventBTGetKnownDevices : public WrtDeviceApis::Commons::IEvent +{ +private: +public: + +private: + std::vector m_Devices; + +public: + EventBTGetKnownDevices() { LogDebug("entered"); } + ~EventBTGetKnownDevices() { } + + void addDevice(BluetoothDeviceData device); + std::vector getDevices(); +}; + +typedef DPL::SharedPtr EventBTGetKnownDevicesPtr; +} +} +} +#endif diff --git a/src/platform/API/Bluetooth/EventBTOnDiscoveryDevices.cpp b/src/platform/API/Bluetooth/EventBTOnDiscoveryDevices.cpp new file mode 100755 index 0000000..3bf0fee --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTOnDiscoveryDevices.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "EventBTOnDiscoveryDevices.h" + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +EventBTOnDiscoveryDevices::EventBTOnDiscoveryDevices() +{ + LogDebug("entered"); +} + +EventBTOnDiscoveryDevices::~EventBTOnDiscoveryDevices() +{ + LogDebug("entered"); +} + +void EventBTOnDiscoveryDevices::addDevice(BluetoothDeviceData device) +{ + m_Devices.push_back(device); +} + +std::vector EventBTOnDiscoveryDevices::getDevices() +{ + return m_Devices; +} + +void EventBTOnDiscoveryDevices::setDiscoveryState(DiscoveryStates state) +{ + m_discoveryState = state; +} + +} +} +} diff --git a/src/platform/API/Bluetooth/EventBTOnDiscoveryDevices.h b/src/platform/API/Bluetooth/EventBTOnDiscoveryDevices.h new file mode 100755 index 0000000..93b05e6 --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTOnDiscoveryDevices.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef TIZENAPIS_API_BLUETOOTH_ON_DISCOVERY_DEVICES_H_ +#define TIZENAPIS_API_BLUETOOTH_ON_DISCOVERY_DEVICES_H_ + +#include +#include +#include +#include +#include +#include "BTDevice.h" + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + + +class EventBTOnDiscoveryDevices : public WrtDeviceApis::Commons::ListenerEvent +{ +public: + typedef enum + { + STARTED, + DISCOVERYING, + FINISHED + } DiscoveryStates; +private: + DiscoveryStates m_discoveryState; + std::vector m_Devices; +public: + EventBTOnDiscoveryDevices(); + ~EventBTOnDiscoveryDevices(); + void setDiscoveryState(DiscoveryStates state); + DiscoveryStates getDiscoveryState() { return m_discoveryState;} + void addDevice(BluetoothDeviceData device); + std::vector getDevices(); +}; + +typedef DPL::SharedPtr EventBTOnDiscoveryDevicesPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter EventBTOnDiscoveryDevicesEmitter; +typedef DPL::SharedPtr EventBTOnDiscoveryDevicesEmitterPtr; + +} +} +} +#endif diff --git a/src/platform/API/Bluetooth/EventBTRegisterRFCOMM.cpp b/src/platform/API/Bluetooth/EventBTRegisterRFCOMM.cpp new file mode 100755 index 0000000..b079a4f --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTRegisterRFCOMM.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "EventBTRegisterRFCOMM.h" + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + + +EventBTRegisterRFCOMM::EventBTRegisterRFCOMM() +{ + LogDebug("entered"); +} +EventBTRegisterRFCOMM::~EventBTRegisterRFCOMM() +{ +} + + +void EventBTRegisterRFCOMM::setSocketData(BluetoothSocketData socket) +{ + m_socket = socket; +} + +BluetoothSocketData EventBTRegisterRFCOMM::getSocketData() +{ + return m_socket; +} + +} +} +} + + diff --git a/src/platform/API/Bluetooth/EventBTRegisterRFCOMM.h b/src/platform/API/Bluetooth/EventBTRegisterRFCOMM.h new file mode 100755 index 0000000..465ae40 --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTRegisterRFCOMM.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_BLUETOOTH_REGISTER_RFCOMM_H_ +#define TIZENAPIS_API_BLUETOOTH_REGISTER_RFCOMM_H_ + +#include +#include +#include +#include +#include "BTDevice.h" + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +class EventBTRegisterRFCOMM : public WrtDeviceApis::Commons::ListenerEvent +{ +public : + typedef enum + { + REGISTER_SUCCESS, + REGISTER_CONNECTED, + REGISTER_DISCONNECTED + } EventBTRegisterConnectionState; + +private: + EventBTRegisterConnectionState m_State; + BluetoothSocketData m_socket; +public: + EventBTRegisterRFCOMM(); + ~EventBTRegisterRFCOMM(); + void setSocketData(BluetoothSocketData socket); + BluetoothSocketData getSocketData(); + void setConnectionState(EventBTRegisterConnectionState state) {m_State = state;} + EventBTRegisterConnectionState getConnectionState() { return m_State;} + +}; + +typedef DPL::SharedPtr EventBTRegisterRFCOMMPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter EventBTRegisterRFCOMMEmitter; +typedef DPL::SharedPtr EventBTRegisterRFCOMMEmitterPtr; + +} +} +} + +#endif diff --git a/src/platform/API/Bluetooth/EventBTSetName.h b/src/platform/API/Bluetooth/EventBTSetName.h new file mode 100644 index 0000000..878d5c9 --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTSetName.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_BLUETOOTH_SET_NAME_H +#define TIZENAPIS_API_BLUETOOTH_SET_NAME_H + +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +class EventBTSetName; + +typedef DPL::SharedPtr EventBTSetNamePtr; + +class EventBTSetName : + public WrtDeviceApis::Commons::IEvent +{ +public: + EventBTSetName(){} + ~EventBTSetName(){} + void setName(std::string name) { m_name = name;} + std::string getName() { return m_name;} +private: + std::string m_name; +}; +} +} +} +#endif + diff --git a/src/platform/API/Bluetooth/EventBTSetPowered.h b/src/platform/API/Bluetooth/EventBTSetPowered.h new file mode 100755 index 0000000..99824ac --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTSetPowered.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_BLUETOOTH_SET_POWERED_H_ +#define TIZENAPIS_API_BLUETOOTH_SET_POWERED_H_ + +#include +#include + + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +class EventBTSetPowered : public WrtDeviceApis::Commons::IEvent +{ +private: + bool m_operation; + bool m_result; + unsigned short m_error; +public: + EventBTSetPowered() + { + LogDebug("entered"); + m_operation = false; + } + + ~EventBTSetPowered() { } + + void setEnable() { m_operation = true;} + void setDisable() { m_operation = false;} + bool isEnableRequested() { return m_operation;} +}; + +typedef DPL::SharedPtr EventBTSetPoweredPtr; +} +} +} +#endif diff --git a/src/platform/API/Bluetooth/EventBTSetVisible.h b/src/platform/API/Bluetooth/EventBTSetVisible.h new file mode 100755 index 0000000..b8f8a47 --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTSetVisible.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_BLUETOOTH_SET_VISIBLE_H_ +#define TIZENAPIS_API_BLUETOOTH_SET_VISIBLE_H_ + +#include +#include + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +class EventBTSetVisible : public WrtDeviceApis::Commons::IEvent +{ +private: + bool m_visible; + unsigned short m_timeout; +public: + EventBTSetVisible() { LogDebug("entered"); m_timeout = 120;} + ~EventBTSetVisible() { } + + void setVisible() { m_visible = true;} + void setInvisible() { m_visible = false;} + void setTimeout(unsigned short timeout) { m_timeout = timeout;} + unsigned short getTimeout() { return m_timeout;} + bool isVisibleRequested() { return m_visible;} + +}; + +typedef DPL::SharedPtr EventBTSetVisiblePtr; +} +} + +} + +#endif diff --git a/src/platform/API/Bluetooth/EventBTSocketNotification.cpp b/src/platform/API/Bluetooth/EventBTSocketNotification.cpp new file mode 100644 index 0000000..9aea743 --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTSocketNotification.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "EventBTSocketNotification.h" + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +EventBTSocketNotification::EventBTSocketNotification() +{ +} + +EventBTSocketNotification::~EventBTSocketNotification() +{ +} + +void EventBTSocketNotification::setSocketData(BluetoothSocketData socket) +{ + m_socketData = socket; +} + +BluetoothSocketData& EventBTSocketNotification::getSocketData() +{ + return m_socketData; +} + +void EventBTSocketNotification::setReadData(char *data, int length) +{ + Assert(data != NULL); + Assert(length != 0); + + for (int i = 0; i < length; i++) + { + m_readData.push_back(data[i]); + } +} + +EventBTReadDataType EventBTSocketNotification::getReadData() +{ + return m_readData; +} + +} +} +} + + diff --git a/src/platform/API/Bluetooth/EventBTSocketNotification.h b/src/platform/API/Bluetooth/EventBTSocketNotification.h new file mode 100644 index 0000000..b300b7b --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTSocketNotification.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_BLUETOOTH_SOCKET_NOTIFICATION_H_ +#define TIZENAPIS_API_BLUETOOTH_SOCKET_NOTIFICATION_H_ + +#include +#include +#include +#include +#include "BTDevice.h" + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +typedef std::vector EventBTReadDataType; + +class EventBTSocketNotification : public WrtDeviceApis::Commons::ListenerEvent +{ +public : + typedef enum + { + CONNECTED, + DISCONNECTED, + DATARECEIVED, + SOCKETERROR + } EventBTSoncketState; + +private: + EventBTSoncketState m_State; + BluetoothSocketData m_socketData; + std::vector m_readData; +public: + EventBTSocketNotification(); + ~EventBTSocketNotification(); + void setSocketData(BluetoothSocketData socket); + BluetoothSocketData& getSocketData(); + void setReadData(char* data, int length); + EventBTReadDataType getReadData(); + void setConnectionState(EventBTSoncketState state) {m_State = state;} + EventBTSoncketState getConnectionState() { return m_State;} + +}; + +typedef DPL::SharedPtr EventBTSocketNotificationPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter EventBTSocketNotificationEmitter; +typedef DPL::SharedPtr EventBTSocketNotificationEmitterPtr; + +} +} +} + +#endif diff --git a/src/platform/API/Bluetooth/EventBTStopDiscovery.h b/src/platform/API/Bluetooth/EventBTStopDiscovery.h new file mode 100644 index 0000000..6204d9f --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTStopDiscovery.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_BLUETOOTH_STOP_DISCOVERY_H_ +#define TIZENAPIS_API_BLUETOOTH_STOP_DISCOVERY_H_ + +#include +#include + + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +class EventBTStopDiscovery : public WrtDeviceApis::Commons::IEvent +{ +private: +public: + EventBTStopDiscovery() + { + } + + ~EventBTStopDiscovery() { } +}; + +typedef DPL::SharedPtr EventBTStopDiscoveryPtr; +} +} +} +#endif + diff --git a/src/platform/API/Bluetooth/EventBTUnregisterRFCOMM.h b/src/platform/API/Bluetooth/EventBTUnregisterRFCOMM.h new file mode 100644 index 0000000..1963d09 --- /dev/null +++ b/src/platform/API/Bluetooth/EventBTUnregisterRFCOMM.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_API_BLUETOOTH_UNREGISTER_RFCOMM_SERVICE_H_ +#define TIZENAPIS_API_BLUETOOTH_UNREGISTER_RFCOMM_SERVICE_H_ + +#include +#include + + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +class EventBTUnregisterRFCOMMService : public WrtDeviceApis::Commons::IEvent +{ +public: + EventBTUnregisterRFCOMMService() { m_serviceSocket = -1;} + ~EventBTUnregisterRFCOMMService() { } + void setUnregisterSocket(int socket) { m_serviceSocket = socket;} + int getUnregisterSocket() { return m_serviceSocket;} +private: + int m_serviceSocket; + +}; + +typedef DPL::SharedPtr EventBTUnregisterRFCOMMServicePtr; +} +} +} +#endif + diff --git a/src/platform/API/Bluetooth/IBluetoothAdapterManager.h b/src/platform/API/Bluetooth/IBluetoothAdapterManager.h new file mode 100755 index 0000000..f90a221 --- /dev/null +++ b/src/platform/API/Bluetooth/IBluetoothAdapterManager.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_API_IBLUETOOTH_ADAPTER_MANAGER_H_ +#define TIZENAPIS_API_IBLUETOOTH_ADAPTER_MANAGER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace TizenApis::Api; + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + + +class IBluetoothAdapterManager : + public WrtDeviceApis::Commons::EventRequestReceiver, + public WrtDeviceApis::Commons::EventRequestReceiver, + public WrtDeviceApis::Commons::EventRequestReceiver, + public WrtDeviceApis::Commons::EventRequestReceiver, + public WrtDeviceApis::Commons::EventRequestReceiver, + public WrtDeviceApis::Commons::EventRequestReceiver, + public WrtDeviceApis::Commons::EventRequestReceiver, + public WrtDeviceApis::Commons::EventRequestReceiver + +{ +public: + virtual ~IBluetoothAdapterManager(); + virtual void setPowered(const EventBTSetPoweredPtr& event) = 0; + virtual void setVisible(const EventBTSetVisiblePtr& event) = 0; + virtual void discoveryDevicesEmitter(const EventBTOnDiscoveryDevicesEmitterPtr& emitter) = 0; + virtual void getKownDevices(const EventBTGetKnownDevicesPtr& event) = 0; + virtual void getDevice(const EventBTGetDevicePtr& event) = 0; + virtual void createBonding(const EventBTCreateDestroyBondingPtr& event) = 0; + virtual void destroyBonding(const EventBTCreateDestroyBondingPtr& event) = 0; + virtual long registerRFCOMMServiceByUUID(const EventBTRegisterRFCOMMEmitterPtr& emitter, + std::string uuid, std::string name, unsigned short int security) = 0; + virtual void unregisterRFCOMMService(const EventBTUnregisterRFCOMMServicePtr& event) = 0; + virtual void stopDiscovery(const EventBTStopDiscoveryPtr& event) = 0; + virtual void setAdapterName(const EventBTSetNamePtr& event) = 0; + virtual std::string getName() = 0; + virtual std::string getAddress() = 0; + virtual bool getPowered() = 0; + virtual bool getVisibility() = 0; + +protected: + IBluetoothAdapterManager(); + + virtual void OnRequestReceived(const EventBTSetPoweredPtr& event) = 0; + virtual void OnRequestReceived(const EventBTSetVisiblePtr& event) = 0; + virtual void OnRequestReceived(const EventBTGetKnownDevicesPtr& event) = 0; + virtual void OnRequestReceived(const EventBTGetDevicePtr& event) = 0; + virtual void OnRequestReceived(const EventBTCreateDestroyBondingPtr& event) = 0; + virtual void OnRequestReceived(const EventBTSetNamePtr& event) = 0; + +}; + +typedef DPL::SharedPtr IBluetoothAdapterManagerPtr; + +} +} +} + +#endif diff --git a/src/platform/API/Bluetooth/IBluetoothDeviceManager.cpp b/src/platform/API/Bluetooth/IBluetoothDeviceManager.cpp new file mode 100644 index 0000000..d6ae22c --- /dev/null +++ b/src/platform/API/Bluetooth/IBluetoothDeviceManager.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "IBluetoothDeviceManager.h" + +using namespace TizenApis::Api; + + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +using namespace WrtDeviceApis::Commons; + +IBluetoothDeviceManager::IBluetoothDeviceManager() : + EventRequestReceiver(ThreadEnum::BLUETOOTH_THREAD) +{ +} + +IBluetoothDeviceManager::~IBluetoothDeviceManager() { +} +} +} +} + diff --git a/src/platform/API/Bluetooth/IBluetoothDeviceManager.h b/src/platform/API/Bluetooth/IBluetoothDeviceManager.h new file mode 100644 index 0000000..4d12cf9 --- /dev/null +++ b/src/platform/API/Bluetooth/IBluetoothDeviceManager.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_API_IBLUETOOTH_DEVICE_MANAGER_H_ +#define TIZENAPIS_API_IBLUETOOTH_DEVICE_MANAGER_H_ + +#include +#include +#include +#include + +using namespace TizenApis::Api; + + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + + +class IBluetoothDeviceManager : + public WrtDeviceApis::Commons::EventRequestReceiver +{ +public: + virtual ~IBluetoothDeviceManager(); + virtual void connectToServiceByUUID(const EventBTConnectToServiceByUUIDPtr& event) = 0; + + virtual void setNameProperty(const std::string name) = 0; + virtual void setAddressProperty(const std::string address) = 0; + virtual void setBondProperty(const bool bonded) = 0; + virtual void setTrustProperty(const bool trused) = 0; + virtual void setConnectProperty(const bool connected) = 0; + virtual void setUuidsProperty(const std::vector uuids) = 0; + virtual void cancelConnectToServiceByUUID() = 0; + + virtual std::string getNameProperty(void) = 0; + virtual std::string getAddressProperty(void) = 0; + virtual bool getBondProperty(void) = 0; + virtual bool getTrustProperty(void) = 0; + virtual bool getConnectProperty(void) = 0; + virtual std::vector getUuidsProperty(void) = 0; + virtual void setDevice(const BluetoothDeviceData device) = 0; + virtual BluetoothDeviceDataClass getClass() = 0; +protected: + IBluetoothDeviceManager(); + virtual void OnRequestReceived(const EventBTConnectToServiceByUUIDPtr& event) = 0; +}; + +typedef DPL::SharedPtr IBluetoothDeviceManagerPtr; + +} +} +} + +#endif diff --git a/src/platform/API/Bluetooth/IBluetoothManager.cpp b/src/platform/API/Bluetooth/IBluetoothManager.cpp new file mode 100755 index 0000000..cc6852e --- /dev/null +++ b/src/platform/API/Bluetooth/IBluetoothManager.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "IBluetoothAdapterManager.h" + +using namespace TizenApis::Api; + + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + +using namespace WrtDeviceApis::Commons; +IBluetoothAdapterManager::IBluetoothAdapterManager() : + EventRequestReceiver(ThreadEnum::BLUETOOTH_THREAD), + EventRequestReceiver(ThreadEnum::BLUETOOTH_THREAD), + EventRequestReceiver(ThreadEnum::BLUETOOTH_THREAD), + EventRequestReceiver(ThreadEnum::BLUETOOTH_THREAD), + EventRequestReceiver(ThreadEnum::BLUETOOTH_THREAD), + EventRequestReceiver(ThreadEnum::BLUETOOTH_THREAD), + EventRequestReceiver(ThreadEnum::BLUETOOTH_THREAD), + EventRequestReceiver(ThreadEnum::BLUETOOTH_THREAD) + +{ +} + +IBluetoothAdapterManager::~IBluetoothAdapterManager() { +} + +} +} +} diff --git a/src/platform/API/Bluetooth/IBluetoothSocketManager.cpp b/src/platform/API/Bluetooth/IBluetoothSocketManager.cpp new file mode 100644 index 0000000..16e6086 --- /dev/null +++ b/src/platform/API/Bluetooth/IBluetoothSocketManager.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "IBluetoothSocketManager.h" + +using namespace TizenApis::Api; + + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + + +IBluetoothSocketManager::IBluetoothSocketManager() +{ +} + +IBluetoothSocketManager::~IBluetoothSocketManager() { +} +} + +} +} + diff --git a/src/platform/API/Bluetooth/IBluetoothSocketManager.h b/src/platform/API/Bluetooth/IBluetoothSocketManager.h new file mode 100644 index 0000000..857bcd1 --- /dev/null +++ b/src/platform/API/Bluetooth/IBluetoothSocketManager.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_API_IBLUETOOTH_SOCKET_MANAGER_H_ +#define TIZENAPIS_API_IBLUETOOTH_SOCKET_MANAGER_H_ + +#include +#include +#include +#include + + +using namespace TizenApis::Api; + + +namespace TizenApis { +namespace Api { +namespace Bluetooth { + + +class IBluetoothSocketManager +{ +public: + virtual ~IBluetoothSocketManager(); + virtual std::string getUUID() = 0; + virtual unsigned int getProtocol() = 0; + virtual unsigned int getState() = 0; + virtual BluetoothDeviceData getPeer() = 0; + virtual int setSocketNotifier(EventBTSocketNotificationEmitterPtr emitter) = 0; + virtual int writeData(const char *data, const unsigned int length) = 0; + virtual EventBTReadDataType readData() = 0; + virtual int close() = 0; + virtual void setSocketData(BluetoothSocketData socketData) = 0; + virtual void setReadData(EventBTReadDataType readData) = 0; +protected: + IBluetoothSocketManager(); +}; + +typedef DPL::SharedPtr IBluetoothSocketManagerPtr; + +} +} +} +#endif diff --git a/src/platform/API/Bluetooth/config.cmake b/src/platform/API/Bluetooth/config.cmake new file mode 100644 index 0000000..e50e0bb --- /dev/null +++ b/src/platform/API/Bluetooth/config.cmake @@ -0,0 +1,14 @@ +get_current_path() + +set(SRCS_PLATFORM_API_BLUETOOTH + ${CURRENT_PATH}/BluetoothFactory.cpp + ${CURRENT_PATH}/EventBTGetKnownDevices.cpp + ${CURRENT_PATH}/EventBTGetDevice.cpp + ${CURRENT_PATH}/EventBTRegisterRFCOMM.cpp + ${CURRENT_PATH}/EventBTOnDiscoveryDevices.cpp + ${CURRENT_PATH}/EventBTSocketNotification.cpp + ${CURRENT_PATH}/IBluetoothManager.cpp + ${CURRENT_PATH}/IBluetoothDeviceManager.cpp + ${CURRENT_PATH}/IBluetoothSocketManager.cpp + PARENT_SCOPE +) diff --git a/src/platform/API/Calendar/CalendarEvent.cpp b/src/platform/API/Calendar/CalendarEvent.cpp new file mode 100755 index 0000000..4442b5f --- /dev/null +++ b/src/platform/API/Calendar/CalendarEvent.cpp @@ -0,0 +1,378 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include "CalendarEvent.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +CalendarEvent::CalendarEvent() : + m_calendarId(UNDEFINED_CALENDAR_ID), + m_status(UNDEFINED_STATUS), + m_categories(new CategoryList()), + m_recurrenceId(0), + m_isDetached(false), + m_calendarType(EVENT_TYPE) +{ +} + +CalendarEvent::~CalendarEvent() +{ +} + +bool CalendarEvent::getIdIsSet() const +{ + return !m_id.IsNull(); +} + +int CalendarEvent::getCalendarId() const +{ + return m_calendarId; +} + +void CalendarEvent::setCalendarId(int value) +{ + m_calendarId = value; +} + +int CalendarEvent::getId() const +{ + return *m_id; +} + +void CalendarEvent::setId(int value) +{ + m_id = value; +} + +void CalendarEvent::resetId() +{ + m_id = DPL::Optional(); +} + +std::string CalendarEvent::getDescription() const +{ + return m_description; +} + +void CalendarEvent::setDescription(const std::string &value) +{ + m_description = value; +} + +std::string CalendarEvent::getSubject() const +{ + return m_subject; +} + +void CalendarEvent::setSubject(const std::string &value) +{ + m_subject = value; +} + +std::time_t CalendarEvent::getStartTime() const +{ + return m_startTime; +} + +void CalendarEvent::setStartTime(std::time_t value) +{ + m_startTime = value; +} + +std::time_t CalendarEvent::getEndTime() const +{ + return m_endTime; +} + +void CalendarEvent::setEndTime(std::time_t value) +{ + m_endTime = value; +} + +std::string CalendarEvent::getLocation() const +{ + return m_location; +} + +void CalendarEvent::setLocation(const std::string &value) +{ + m_location = value; +} + +EventRecurrenceRulePtr CalendarEvent::getRecurrenceRule() const +{ + return m_recurrence; +} + +void CalendarEvent::setRecurrenceRule(EventRecurrenceRulePtr value) +{ + m_recurrence = value; +} + +CalendarEvent::EventStatus CalendarEvent::getStatus() const +{ + return m_status == UNDEFINED_STATUS ? TENTATIVE_STATUS : m_status; +} + +void CalendarEvent::setStatus(EventStatus value) +{ + m_status = value; +} + +std::vector CalendarEvent::getAlarmsTick() const +{ + return m_alarmsTick; +} + +void CalendarEvent::setAlarmsTick(std::vector &value) +{ + m_alarmsTick = value; +} + +std::vector CalendarEvent::getAlarmsType() const +{ + return m_alarmsType; +} + +void CalendarEvent::setAlarmsType(std::vector &value) +{ + m_alarmsType = value; +} + +CategoryListPtr CalendarEvent::getCategories() const +{ + return m_categories; +} +void CalendarEvent::setCategories(const CategoryListPtr &value) +{ + m_categories = value; +} + +void CalendarEvent::display() const +{ + LogDebug("m_id " << m_id); + LogDebug("m_calendarId " << m_calendarId); + LogDebug("m_description " << m_description); + LogDebug("m_subject " << m_subject); + LogDebug("m_startTime " << m_startTime); + LogDebug("m_endTime " << m_endTime); + LogDebug("m_location " << m_location); + LogDebug("m_recurrence " << m_recurrence); + LogDebug("m_status " << m_status); + LogDebug("m_isAllDay " << m_isAllDay); + LogDebug("m_organizer " << m_organizer); + LogDebug("m_lastModifiedDate " << m_lastModifiedDate); + LogDebug("m_visibility " << m_visibility); + LogDebug("m_availability " << m_availability); +} + +bool CalendarEvent::validate() const +{ + if (m_status == INVALID_STATUS) { + LogError("Incorrect status value detected"); + return false; + } + return true; +} + +bool CalendarEvent::getIsAllDay() const +{ + return m_isAllDay; +} + +void CalendarEvent::setIsAllDay(bool value) +{ + m_isAllDay = value; +} + +std::string CalendarEvent::getOrganizer() const +{ + return m_organizer; +} + +void CalendarEvent::setOrganizer(const std::string &value) +{ + m_organizer = value; +} + +std::time_t CalendarEvent::getLastModifiedDate() const +{ + return m_lastModifiedDate; +} + +void CalendarEvent::setLastModifiedDate(std::time_t value) +{ + m_lastModifiedDate = value; +} + +CalendarEvent::EventVisibility CalendarEvent::getVisibility() const +{ + return m_visibility == UNDEFINED_VISIBILITY ? PUBLIC_VISIBILITY : m_visibility; +} + +void CalendarEvent::setVisibility(EventVisibility value) +{ + m_visibility = value; +} + +CalendarEvent::EventAvailability CalendarEvent::getAvailability() const +{ + return m_availability == UNDEFINED_AVAILABILITY ? FREE_FB : m_availability; +} + +void CalendarEvent::setAvailability(EventAvailability value) +{ + m_availability = value; +} + +std::string CalendarEvent::getUId() const +{ + return m_uid; +} + +void CalendarEvent::setUId(const std::string &value) +{ + m_uid = value; +} + +std::time_t CalendarEvent::getRecurrenceId() const +{ + return m_recurrenceId; +} + +void CalendarEvent::setRecurrenceId(std::time_t value) +{ + m_recurrenceId = value; +} + +EventAttendeeListPtr CalendarEvent::getAttendees() const +{ + return m_attendees; +} + +void CalendarEvent::setAttendees(const EventAttendeeListPtr &value) +{ + m_attendees = value; +} + +bool CalendarEvent::getIsDetached() const +{ + return m_isDetached; +} + +void CalendarEvent::setIsDetached(bool value) +{ + m_isDetached = value; +} + +AttributeListPtr CalendarEvent::getAttributesOfInterest() const +{ + return m_attributesOfInterest; +} + +void CalendarEvent::setAttributesOfInterest(AttributeListPtr value) +{ + m_attributesOfInterest = value; +} + +double CalendarEvent::getLatitude() const +{ + return m_latitude; +} + +void CalendarEvent::setLatitude(double value) +{ + m_latitude = value; +} + +double CalendarEvent::getLongitude() const +{ + return m_longitude; +} + +void CalendarEvent::setLongitude(double value) +{ + m_longitude = value; +} + +std::string CalendarEvent::getTimeZone() const +{ + return m_timeZone; +} + +void CalendarEvent::setTimeZone(std::string value) +{ + m_timeZone = value; +} + +CalendarEvent::TaskPriority CalendarEvent::getPriority() const +{ + return m_priority; +} + +void CalendarEvent::setPriority(TaskPriority value) +{ + m_priority = value; +} + +std::time_t CalendarEvent::getCreatedDate() const +{ + return m_createdDate; +} + +void CalendarEvent::setCreatedDate(std::time_t value) +{ + m_createdDate = value; +} + +std::time_t CalendarEvent::getCompletedDate() const +{ + return m_completedDate; +} + +void CalendarEvent::setCompletedDate(std::time_t value) +{ + m_completedDate = value; +} + +int CalendarEvent::getProgress() const +{ + return m_progress; +} + +void CalendarEvent::setProgress(int value) +{ + m_progress = value; +} + +CalendarEvent::CalendarType CalendarEvent::getCalendarType() const +{ + return m_calendarType; +} + +void CalendarEvent::setCalendarType(CalendarType type) +{ + m_calendarType = type; +} + +} +} +} diff --git a/src/platform/API/Calendar/CalendarEvent.h b/src/platform/API/Calendar/CalendarEvent.h new file mode 100755 index 0000000..61804a8 --- /dev/null +++ b/src/platform/API/Calendar/CalendarEvent.h @@ -0,0 +1,251 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_CALENDAR_EVENT_H_ +#define _ABSTRACT_LAYER_CALENDAR_EVENT_H_ + +#include +#include +#include +#include +#include + +#include "EventAttendee.h" +#include "EventRecurrenceRule.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +typedef std::vector CategoryList; +typedef DPL::SharedPtr CategoryListPtr; + +typedef std::vector AttributeList; +typedef DPL::SharedPtr AttributeListPtr; + +/* This object represents a single calendar event */ +class CalendarEvent +{ + public: + + static const int UNDEFINED_CALENDAR_ID = -1; + + typedef enum + { + TENTATIVE_STATUS, + CONFIRMED_STATUS, + CANCELLED_STATUS, + NEEDS_ACTION_STATUS, + IN_PROCESS_STATUS, + COMPLETED_STATUS, + INVALID_STATUS = 10000, + UNDEFINED_STATUS + } EventStatus; + + typedef enum + { + NO_ALARM, + SILENT_ALARM, + SOUND_ALARM, + INVALID_ALARM_TYPE = 10000, + UNDEFINED_ALARM_TYPE + } EventAlarmType; + + typedef enum + { + PUBLIC_VISIBILITY, + PRIVATE_VISIBILITY, + CONFIDENTIAL_VISIBILITY, + INVALID_VISIBILITY = 10000, + UNDEFINED_VISIBILITY + } EventVisibility; + + typedef enum + { + BUSY_FB, + BUSY_UNAVAILABLE_FB, + FREE_FB, + BUSY_TENTATIVE_FB, + INVALID_AVAILABILITY = 10000, + UNDEFINED_AVAILABILITY + } EventAvailability; + + typedef enum + { + LOW_PRIORITY, + MEDIUM_PRIORITY, + HIGH_PRIORITY, + INVALID_PRIORITY = 10000, + UNDEFINED_PRIORITY + } TaskPriority; + + typedef enum + { + ICALENDAR_20, + VCALENDAR_10, + INVALID_FORMAT = 10000, + UNDEFINED_FORMAT + } VObjectFormat; + + typedef enum + { + EVENT_TYPE = 0, + TASK_TYPE, + } CalendarType; + + + CalendarEvent(); + virtual ~CalendarEvent(); + + int getId() const; + void setId(int value); + void resetId(); + bool getIdIsSet() const; + + int getCalendarId() const; + void setCalendarId(int value); + + std::string getDescription() const; + void setDescription(const std::string &value); + + std::string getSubject() const; + void setSubject(const std::string &value); + + std::time_t getStartTime() const; + void setStartTime(std::time_t value); + + std::time_t getEndTime() const; + void setEndTime(std::time_t value); + + std::string getLocation() const; + void setLocation(const std::string &value); + + EventRecurrenceRulePtr getRecurrenceRule() const; + void setRecurrenceRule(EventRecurrenceRulePtr value); + + EventStatus getStatus() const; + void setStatus(EventStatus value); + + std::vector getAlarmsTick() const; + void setAlarmsTick(std::vector &value); + + std::vector getAlarmsType() const; + void setAlarmsType(std::vector &value); + + CategoryListPtr getCategories() const; + void setCategories(const CategoryListPtr &value); + + void display() const; + bool validate() const; + + bool getIsAllDay() const; + void setIsAllDay(bool value); + + std::time_t getLastModifiedDate() const; + void setLastModifiedDate(std::time_t value); + + std::string getOrganizer() const; + void setOrganizer(const std::string &value); + + EventVisibility getVisibility() const; + void setVisibility(EventVisibility value); + + EventAvailability getAvailability() const; + void setAvailability(EventAvailability value); + + std::string getUId() const; + void setUId(const std::string &value); + + std::time_t getRecurrenceId() const; + void setRecurrenceId(std::time_t value); + + EventAttendeeListPtr getAttendees() const; + void setAttendees(const EventAttendeeListPtr &value); + + bool getIsDetached() const; + void setIsDetached(bool value); + + void setAttributesOfInterest(AttributeListPtr value); + AttributeListPtr getAttributesOfInterest() const; + + void setLatitude(double value); + double getLatitude() const; + + void setLongitude(double value); + double getLongitude() const; + + void setTimeZone(std::string value); + std::string getTimeZone() const; + + TaskPriority getPriority() const; + void setPriority(TaskPriority value); + + std::time_t getCreatedDate() const; + void setCreatedDate(std::time_t value); + + std::time_t getCompletedDate() const; + void setCompletedDate(std::time_t value); + + int getProgress() const; + void setProgress(int value); + + CalendarType getCalendarType() const; + void setCalendarType(CalendarType type); + + protected: + DPL::Optional m_id; + int m_calendarId; + std::string m_description; + std::string m_subject; + std::time_t m_startTime; + std::time_t m_endTime; + std::string m_location; + EventRecurrenceRulePtr m_recurrence; + EventStatus m_status; + std::vector m_alarmsTick; + std::vector m_alarmsType; + CategoryListPtr m_categories; + bool m_isAllDay; + std::string m_organizer; + std::time_t m_lastModifiedDate; + EventVisibility m_visibility; + EventAvailability m_availability; + std::string m_uid; + std::time_t m_recurrenceId; + EventAttendeeListPtr m_attendees; + bool m_isDetached; + AttributeListPtr m_attributesOfInterest; + double m_latitude; + double m_longitude; + std::string m_timeZone; + TaskPriority m_priority; + std::time_t m_createdDate; + std::time_t m_completedDate; + int m_progress; + CalendarType m_calendarType; +}; + +typedef DPL::SharedPtr CalendarEventPtr; +typedef std::vector CalendarEventList; +typedef DPL::SharedPtr CalendarEventListPtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_CALENDAR_EVENT_H_ */ + diff --git a/src/platform/API/Calendar/CalendarFactory.cpp b/src/platform/API/Calendar/CalendarFactory.cpp new file mode 100755 index 0000000..5579583 --- /dev/null +++ b/src/platform/API/Calendar/CalendarFactory.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "CalendarFactory.h" +#include "ICalendarManager.h" +#include "ICalendar.h" +#include + +using namespace TizenApis::Platform::Calendar; + +namespace TizenApis { +namespace Api { +namespace Calendar { + +ICalendarManagerPtr CalendarFactory::createCalendarManagerObject() +{ + ICalendarManagerPtr result(new CalendarManager()); + return result; +} + +ICalendarPtr CalendarFactory::createCalendarObject() +{ + ICalendarPtr result(new TizenApis::Platform::Calendar::Calendar()); + return result; +} + +CalendarFactory& CalendarFactory::getInstance() +{ + static CalendarFactory theInstance; + return theInstance; +} + +} +} +} \ No newline at end of file diff --git a/src/platform/API/Calendar/CalendarFactory.h b/src/platform/API/Calendar/CalendarFactory.h new file mode 100755 index 0000000..c493fbd --- /dev/null +++ b/src/platform/API/Calendar/CalendarFactory.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_CALENDAR_FACTORY_H_ +#define _ABSTRACT_LAYER_CALENDAR_FACTORY_H_ + +#include "ICalendarManager.h" +#include "ICalendar.h" +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class CalendarFactory : private DPL::Noncopyable +{ + private: + CalendarFactory() + { + } + public: + static CalendarFactory& getInstance(); + ICalendarManagerPtr createCalendarManagerObject(); + ICalendarPtr createCalendarObject(); +}; + +} +} +} + +#endif /* _ABSTRACT_LAYER_CALENDAR_FACTORY_H_ */ diff --git a/src/platform/API/Calendar/EventAlarm.cpp b/src/platform/API/Calendar/EventAlarm.cpp new file mode 100755 index 0000000..9f58bb0 --- /dev/null +++ b/src/platform/API/Calendar/EventAlarm.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "EventAlarm.h" +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +EventAlarm::EventAlarm() +{ + m_absoluteDate = 0; + m_minutes = 0; + m_days = 0; +} +EventAlarm::~EventAlarm() +{ +} + +std::time_t EventAlarm::getAbsoluteDate() const +{ + return m_absoluteDate; +} +void EventAlarm::setAbsoluteDate(const std::time_t &value) +{ + m_absoluteDate = value; +} + +std::string EventAlarm::getTimeZone() const +{ + return m_timeZone; +} +void EventAlarm::setTimeZone(const std::string &value) +{ + m_timeZone = value; +} + +long EventAlarm::getMinutes() const +{ + return m_minutes; +} +void EventAlarm::setMinutes(const long &value) +{ + m_minutes = value; +} + +long EventAlarm::getDays() const +{ + return m_days; +} +void EventAlarm::setDays(const long &value) +{ + m_days = value; +} + +std::vector EventAlarm::getMethods() const +{ + return m_methods; +} +void EventAlarm::setMethods(const std::vector &value) +{ + m_methods = value; +} + +} +} +} diff --git a/src/platform/API/Calendar/EventAlarm.h b/src/platform/API/Calendar/EventAlarm.h new file mode 100755 index 0000000..4e3062c --- /dev/null +++ b/src/platform/API/Calendar/EventAlarm.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _EVENT_ALARM_H_ +#define _EVENT_ALARM_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class EventAlarm +{ + public: + EventAlarm(); + virtual ~EventAlarm(); + + std::time_t getAbsoluteDate() const; + void setAbsoluteDate(const std::time_t &value); + + std::string getTimeZone() const; + void setTimeZone(const std::string &value); + + long getMinutes() const; + void setMinutes(const long &value); + + long getDays() const; + void setDays(const long &value); + + std::vector getMethods() const; + void setMethods(const std::vector &value); + + protected: + std::time_t m_absoluteDate; + std::string m_timeZone; + long m_minutes; + long m_days; + std::vector m_methods; +}; + +typedef DPL::SharedPtr EventAlarmPtr; +typedef std::vector EventAlarmList; +typedef DPL::SharedPtr EventAlarmListPtr; + +} +} +} + +#endif /* _EVENT_ALARM_H_ */ diff --git a/src/platform/API/Calendar/EventAttendee.cpp b/src/platform/API/Calendar/EventAttendee.cpp new file mode 100755 index 0000000..604379a --- /dev/null +++ b/src/platform/API/Calendar/EventAttendee.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "EventAttendee.h" +#include + +/** + * @file EventAttendee.cpp + * + * @version 0.1 + */ + +namespace TizenApis { +namespace Api { +namespace Calendar { + +EventAttendee::EventAttendee() +{ +} + +EventAttendee::~EventAttendee() +{ +} + +std::string EventAttendee::getName() const +{ + return m_name; +} + +void EventAttendee::setName(const std::string &value) +{ + m_name = value; +} + +std::string EventAttendee::getURI() const +{ + return m_uri; +} + +void EventAttendee::setURI(const std::string &value) +{ + m_uri = value; +} + +EventAttendee::EventAttendeeRole EventAttendee::getRole() const +{ + return m_role; +} + +void EventAttendee::setRole(EventAttendeeRole value) +{ + m_role = value; +} + +EventAttendee::EventAttendeeStatus EventAttendee::getStatus() const +{ + return m_status; +} + +void EventAttendee::setStatus(EventAttendeeStatus value) +{ + m_status = value; +} + +bool EventAttendee::getRSVP() const +{ + return m_RSVP; +} + +void EventAttendee::setRSVP(bool value) +{ + m_RSVP = value; +} + +EventAttendee::EventAttendeeType EventAttendee::getType() const +{ + return m_type; +} + +void EventAttendee::setType(EventAttendeeType value) +{ + m_type = value; +} + +std::string EventAttendee::getGroup() const +{ + return m_group; +} + +void EventAttendee::setGroup(const std::string &value) +{ + m_group = value; +} + +std::string EventAttendee::getDelegatorURI() const +{ + return m_delegatorURI; +} + +void EventAttendee::setDelegatorURI(const std::string &value) +{ + m_delegatorURI = value; +} + + +std::string EventAttendee::getDelegateURI() const +{ + return m_delegateURI; +} + +void EventAttendee::setDelegateURI(const std::string &value) +{ + m_delegateURI = value; +} + +std::string EventAttendee::getPersonId() const +{ + return m_uid; +} + +void EventAttendee::setPersonId(const std::string &value) +{ + m_uid = value; +} + +} +} +} diff --git a/src/platform/API/Calendar/EventAttendee.h b/src/platform/API/Calendar/EventAttendee.h new file mode 100755 index 0000000..3ec16be --- /dev/null +++ b/src/platform/API/Calendar/EventAttendee.h @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_EVENT_ATTENDEE_H_ +#define _ABSTRACT_LAYER_EVENT_ATTENDEE_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class EventAttendee +{ + public: + + typedef enum + { + REQ_PARTICIPANT_ROLE, + OPT_PARTICIPANT_ROLE, + NON_PARTICIPANT_ROLE, + CHAIR_ROLE, + INVALID_ATTENDEE_ROLE = 10000, + UNDEFINED_ATTENDEE_ROLE /* should be used only to mark a fact filter is not set */ + } EventAttendeeRole; + + typedef enum + { + PENDING_AT_STATUS, + ACCEPTED_AT_STATUS, + DECLINED_AT_STATUS, + TENTATIVE_AT_STATUS, + DELEGATED_AT_STATUS, + COMPLETED_AT_STATUS, + IN_PROCESS_AT_STATUS, + INVALID_ATTENDEE_STATUS = 10000, + UNDEFINED_ATTENDEE_STATUS /* should be used only to mark a fact filter is not set */ + } EventAttendeeStatus; + + typedef enum + { + INDIVIDUAL_TYPE, + GROUP_TYPE, + RESOURCE_TYPE, + ROOM_TYPE, + UNKNOWN_TYPE, + INVALID_ATTENDEE_TYPE = 10000, + UNDEFINED_ATTENDEE_TYPE /* should be used only to mark a fact filter is not set */ + } EventAttendeeType; + + EventAttendee(); + virtual ~EventAttendee(); + + std::string getName() const; + void setName(const std::string &value); + + std::string getURI() const; + void setURI(const std::string &value); + + EventAttendeeRole getRole() const; + void setRole(EventAttendeeRole value); + + EventAttendeeStatus getStatus() const; + void setStatus(EventAttendeeStatus value); + + bool getRSVP() const; + void setRSVP(bool value); + + EventAttendeeType getType() const; + void setType(EventAttendeeType value); + + std::string getGroup() const; + void setGroup(const std::string &value); + + std::string getDelegatorURI() const; + void setDelegatorURI(const std::string &value); + + std::string getDelegateURI() const; + void setDelegateURI(const std::string &value); + + std::string getPersonId() const; + void setPersonId(const std::string &value); + + protected: + std::string m_name; + std::string m_uri; + EventAttendeeRole m_role; + EventAttendeeStatus m_status; + bool m_RSVP; + EventAttendeeType m_type; + std::string m_group; + std::string m_delegatorURI; + std::string m_delegateURI; + std::string m_uid; // needs PersonId class! +}; + +typedef DPL::SharedPtr EventAttendeePtr; +typedef std::vector EventAttendeeList; +typedef DPL::SharedPtr EventAttendeeListPtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_EVENT_ATTENDEE_H_ */ diff --git a/src/platform/API/Calendar/EventFilter.cpp b/src/platform/API/Calendar/EventFilter.cpp new file mode 100755 index 0000000..c44a9d9 --- /dev/null +++ b/src/platform/API/Calendar/EventFilter.cpp @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "EventFilter.h" +#include + +/** + * @file EventFilter.cpp + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + */ + +namespace TizenApis { +namespace Api { +namespace Calendar { + +EventFilter::EventFilter() +{ +} + +EventFilter::~EventFilter() +{ +} + +std::string EventFilter::getIdFilter() const +{ + return *m_id; +} + +void EventFilter::setIdFilter(const std::string &value) +{ + m_id = value; +} + +int EventFilter::getCalendarIdFilter() const +{ + return *m_calendarId; +} + +void EventFilter::setCalendarIdFilter(int value) +{ + m_calendarId = value; +} + +std::string EventFilter::getDescriptionFilter() const +{ + return *m_description; +} + +void EventFilter::setDescriptionFilter(const std::string &value) +{ + m_description = value; +} + +std::string EventFilter::getSubjectFilter() const +{ + return *m_subject; +} + +void EventFilter::setSubjectFilter(const std::string &value) +{ + m_subject = value; +} + +time_t EventFilter::getStartTimeMinFilter() const +{ + return *m_startTimeMin; +} + +time_t EventFilter::getStartTimeMaxFilter() const +{ + return *m_startTimeMax; +} + +void EventFilter::setStartTimeMinFilter(time_t value) +{ + m_startTimeMin = value; +} + +void EventFilter::setStartTimeMaxFilter(time_t value) +{ + m_startTimeMax = value; +} + +void EventFilter::setStartTimeFilter(time_t value) +{ + setStartTimeMinFilter(value); + setStartTimeMaxFilter(value); +} + +time_t EventFilter::getEndTimeMinFilter() const +{ + return *m_endTimeMin; +} + +time_t EventFilter::getEndTimeMaxFilter() const +{ + return *m_endTimeMax; +} + +void EventFilter::setEndTimeMinFilter(time_t value) +{ + m_endTimeMin = value; +} + +void EventFilter::setEndTimeMaxFilter(time_t value) +{ + m_endTimeMax = value; +} + +void EventFilter::setEndTimeFilter(time_t value) +{ + setEndTimeMinFilter(value); + setEndTimeMaxFilter(value); +} + +std::string EventFilter::getLocationFilter() const +{ + return *m_location; +} + +void EventFilter::setLocationFilter(const std::string &value) +{ + m_location = value; +} + +std::vector EventFilter::getRecurrenceFilter() +const +{ + return m_recurrence; +} + +void EventFilter::addRecurrenceFilter(EventRecurrenceRule::EventRecurrence value) +{ + m_recurrence.push_back(value); +} + +std::vector EventFilter::getStatusFilter() const +{ + return m_status; +} + +void EventFilter::addStatusFilter(CalendarEvent::EventStatus value) +{ + m_status.push_back(value); +} + +time_t EventFilter::getAlarmTimeMinFilter() const +{ + return *m_alarmTimeMin; +} + +time_t EventFilter::getAlarmTimeMaxFilter() const +{ + return *m_alarmTimeMax; +} + +void EventFilter::setAlarmTimeMinFilter(time_t value) +{ + m_alarmTimeMin = value; +} + +void EventFilter::setAlarmTimeMaxFilter(time_t value) +{ + m_alarmTimeMax = value; +} + +void EventFilter::setAlarmTimeFilter(time_t value) +{ + setAlarmTimeMinFilter(value); + setAlarmTimeMaxFilter(value); +} + +std::vector EventFilter::getAlarmTypeFilter() +const +{ + return m_alarmType; +} + +void EventFilter::addAlarmTypeFilter(CalendarEvent::EventAlarmType value) +{ + m_alarmType.push_back(value); +} + +std::string EventFilter::getCategoryFilter() const +{ + return *m_category; +} + +void EventFilter::setCategoryFilter(const std::string &category) +{ + m_category = category; +} + +bool EventFilter::getIdIsSet() const +{ + return !m_id.IsNull(); +} + +bool EventFilter::getCalendarIdIsSet() const +{ + return !m_calendarId.IsNull(); +} + +bool EventFilter::getDescriptionIsSet() const +{ + return !m_description.IsNull(); +} + +bool EventFilter::getSubjectIsSet() const +{ + return !m_subject.IsNull(); +} + +bool EventFilter::getStartTimeMinIsSet() const +{ + return !m_startTimeMin.IsNull(); +} + +bool EventFilter::getStartTimeMaxIsSet() const +{ + return !m_startTimeMax.IsNull(); +} + +bool EventFilter::getEndTimeMinIsSet() const +{ + return !m_endTimeMin.IsNull(); +} + +bool EventFilter::getEndTimeMaxIsSet() const +{ + return !m_endTimeMax.IsNull(); +} + +bool EventFilter::getLocationIsSet() const +{ + return !m_location.IsNull(); +} + +bool EventFilter::getRecurrenceIsSet() const +{ + return !m_recurrence.empty(); +} + +bool EventFilter::getStatusIsSet() const +{ + return !m_status.empty(); +} + +bool EventFilter::getAlarmTimeMinIsSet() const +{ + return !m_alarmTimeMin.IsNull(); +} + +bool EventFilter::getAlarmTimeMaxIsSet() const +{ + return !m_alarmTimeMax.IsNull(); +} + +bool EventFilter::getAlarmTypeIsSet() const +{ + return !m_alarmType.empty(); +} + +bool EventFilter::getCategoryIsSet() const +{ + return !m_category.IsNull(); +} + +} +} +} diff --git a/src/platform/API/Calendar/EventFilter.h b/src/platform/API/Calendar/EventFilter.h new file mode 100755 index 0000000..69259e7 --- /dev/null +++ b/src/platform/API/Calendar/EventFilter.h @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_IEVENT_FILTER_H_ +#define _ABSTRACT_LAYER_IEVENT_FILTER_H_ + +#include +#include +#include +#include +#include +#include "CalendarEvent.h" +#include "EventRecurrenceRule.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class EventFilter +{ + public: + + EventFilter(); + virtual ~EventFilter(); + + std::string getIdFilter() const; + void setIdFilter(const std::string &value); + + int getCalendarIdFilter() const; + void setCalendarIdFilter(int value); + + std::string getDescriptionFilter() const; + void setDescriptionFilter(const std::string &value); + + std::string getSubjectFilter() const; + void setSubjectFilter(const std::string &value); + + std::time_t getStartTimeMinFilter() const; + std::time_t getStartTimeMaxFilter() const; + void setStartTimeMinFilter(std::time_t value); + void setStartTimeMaxFilter(std::time_t value); + void setStartTimeFilter(std::time_t value); + + std::time_t getEndTimeMinFilter() const; + std::time_t getEndTimeMaxFilter() const; + void setEndTimeMinFilter(std::time_t value); + void setEndTimeMaxFilter(std::time_t value); + void setEndTimeFilter(std::time_t value); + + std::string getLocationFilter() const; + void setLocationFilter(const std::string &value); + + std::vector getRecurrenceFilter() const; + void addRecurrenceFilter(EventRecurrenceRule::EventRecurrence value); + + std::vector getStatusFilter() const; + void addStatusFilter(CalendarEvent::EventStatus value); + + std::time_t getAlarmTimeMinFilter() const; + std::time_t getAlarmTimeMaxFilter() const; + void setAlarmTimeMinFilter(std::time_t value); + void setAlarmTimeMaxFilter(std::time_t value); + void setAlarmTimeFilter(std::time_t value); + + std::vector getAlarmTypeFilter() const; + void addAlarmTypeFilter(CalendarEvent::EventAlarmType value); + + std::string getCategoryFilter() const; + void setCategoryFilter(const std::string &category); + + bool getIdIsSet() const; + bool getCalendarIdIsSet() const; + bool getDescriptionIsSet() const; + bool getSubjectIsSet() const; + bool getStartTimeMinIsSet() const; + bool getStartTimeMaxIsSet() const; + bool getEndTimeMinIsSet() const; + bool getEndTimeMaxIsSet() const; + bool getLocationIsSet() const; + bool getRecurrenceIsSet() const; + bool getStatusIsSet() const; + bool getAlarmTimeMinIsSet() const; + bool getAlarmTimeMaxIsSet() const; + bool getAlarmTypeIsSet() const; + bool getCategoryIsSet() const; + + protected: + DPL::Optional m_id; + DPL::Optional m_calendarId; + DPL::Optional m_description; + DPL::Optional m_subject; + DPL::Optional m_startTimeMin; + DPL::Optional m_startTimeMax; + DPL::Optional m_endTimeMin; + DPL::Optional m_endTimeMax; + DPL::Optional m_location; + std::vector m_recurrence; + std::vector m_status; + std::vector m_alarmType; + DPL::Optional m_alarmTimeMin; + DPL::Optional m_alarmTimeMax; + DPL::Optional m_category; +}; + +typedef DPL::SharedPtr EventFilterPtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_IEVENT_FILTER_H_ */ diff --git a/src/platform/API/Calendar/EventId.cpp b/src/platform/API/Calendar/EventId.cpp new file mode 100755 index 0000000..73ff075 --- /dev/null +++ b/src/platform/API/Calendar/EventId.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "EventId.h" +#include + +/** + * @file EventId.cpp + * + * @version 0.1 + */ + +namespace TizenApis { +namespace Api { +namespace Calendar { + +EventId::EventId() +{ + m_recurrenceId = 0; +} + +EventId::~EventId() +{ +} + +std::string EventId::getUId() const +{ + return m_uid; +} + +void EventId::setUId(const std::string &value) +{ + m_uid = value; +} + +std::time_t EventId::getRecurrenceId() const +{ + return m_recurrenceId; +} + +void EventId::setRecurrenceId(const std::time_t &value) +{ + m_recurrenceId = value; +} + +std::string EventId::getTimeZone() const +{ + return m_timeZone; +} + +void EventId::setTimeZone(const std::string &value) +{ + m_timeZone = value; +} + +CalendarEvent::CalendarType EventId::getCalendarType() const +{ + return m_calendarType; +} + +void EventId::setCalendarType(CalendarEvent::CalendarType type) +{ + m_calendarType = type; +} + +} +} +} diff --git a/src/platform/API/Calendar/EventId.h b/src/platform/API/Calendar/EventId.h new file mode 100755 index 0000000..1a3d8c3 --- /dev/null +++ b/src/platform/API/Calendar/EventId.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_EVENT_ID_H_ +#define _ABSTRACT_LAYER_EVENT_ID_H_ + +#include +#include +#include +#include + +#include "CalendarEvent.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class EventId +{ + public: + + EventId(); + virtual ~EventId(); + + std::string getUId() const; + void setUId(const std::string &value); + + std::time_t getRecurrenceId() const; + void setRecurrenceId(const std::time_t &value); + + std::string getTimeZone() const; + void setTimeZone(const std::string &value); + + CalendarEvent::CalendarType getCalendarType() const; + void setCalendarType(CalendarEvent::CalendarType type); + + protected: + std::string m_uid; + std::time_t m_recurrenceId; + std::string m_timeZone; + CalendarEvent::CalendarType m_calendarType; +}; + +typedef DPL::SharedPtr EventIdPtr; +typedef std::vector EventIdList; +typedef DPL::SharedPtr EventIdListPtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_EVENT_ID_H_ */ diff --git a/src/platform/API/Calendar/EventRecurrenceRule.cpp b/src/platform/API/Calendar/EventRecurrenceRule.cpp new file mode 100755 index 0000000..d35c1e1 --- /dev/null +++ b/src/platform/API/Calendar/EventRecurrenceRule.cpp @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "EventRecurrenceRule.h" +#include +#include + +/** + * @file EventRecurrenceRule.cpp + * + * @version 0.1 + */ + +namespace TizenApis { +namespace Api { +namespace Calendar { + +EventRecurrenceRule::EventRecurrenceRule() : + m_frequency(NO_RECURRENCE), + m_occurrenceCount(-1), + m_setPosition(false) +{ +} + +EventRecurrenceRule::~EventRecurrenceRule() +{ +} + +EventRecurrenceRule::EventRecurrence EventRecurrenceRule::getFrequency() const +{ + return m_frequency; +} + +void EventRecurrenceRule::setFrequency(const EventRecurrenceRule::EventRecurrence &value) +{ + m_frequency = value; +} + +int EventRecurrenceRule::getInterval() const +{ + return m_interval; +} + +void EventRecurrenceRule::setInterval(const int &value) +{ + m_interval = value; +} + +bool EventRecurrenceRule::isEndDateSet() const +{ + return !m_endDate.IsNull(); +} + +time_t EventRecurrenceRule::getEndDate() const +{ + return *m_endDate; +} + +void EventRecurrenceRule::setEndDate(time_t value) +{ + m_endDate = value; +} + +void EventRecurrenceRule::resetEndDate() +{ + m_endDate = DPL::Optional(); +} + +long EventRecurrenceRule::getOccurrenceCount() const +{ + return m_occurrenceCount; +} +void EventRecurrenceRule::setOccurrenceCount(long value) +{ + m_occurrenceCount = value; +} + +std::vector EventRecurrenceRule::getDaysOfTheMonth() const +{ + return m_daysOfTheMonth; +} + +void EventRecurrenceRule::setDaysOfTheMonth(std::vector value) +{ + m_daysOfTheMonth = value; +} + +std::vector EventRecurrenceRule::getDaysOfTheWeek() const +{ + return m_daysOfTheWeek; +} + +void EventRecurrenceRule::setDaysOfTheWeek(std::vector value) +{ + m_daysOfTheWeek = value; +} + +std::vector EventRecurrenceRule::getDaysOfTheYear() const +{ + return m_daysOfTheYear; +} + +void EventRecurrenceRule::setDaysOfTheYear(std::vector value) +{ + m_daysOfTheYear = value; +} + +std::vector EventRecurrenceRule::getWeeksOfTheYear() const +{ + return m_weeksOfTheYear; +} + +void EventRecurrenceRule::setWeeksOfTheYear(std::vector value) +{ + m_weeksOfTheYear = value; +} + +bool EventRecurrenceRule::getSetPosition() const +{ + return m_setPosition; +} + +void EventRecurrenceRule::setSetPosition(bool value) +{ + m_setPosition = value; +} + +std::vector EventRecurrenceRule::getExceptions() const +{ + return m_exceptions; +} + +void EventRecurrenceRule::setExceptions(std::vector value) +{ + m_exceptions = value; +} + +std::string EventRecurrenceRule::getTimeZone() const +{ + return m_timeZone; +} + +void EventRecurrenceRule::setTimeZone(std::string value) +{ + m_timeZone = value; +} + +} +} +} diff --git a/src/platform/API/Calendar/EventRecurrenceRule.h b/src/platform/API/Calendar/EventRecurrenceRule.h new file mode 100755 index 0000000..f8b4e3c --- /dev/null +++ b/src/platform/API/Calendar/EventRecurrenceRule.h @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _EVENT_RECURRENCE_RULE_H_ +#define _EVENT_RECURRENCE_RULE_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class EventRecurrenceRule +{ + public: + + typedef enum + { + NO_RECURRENCE, //The calendar entry occurs once + DAILY_RECURRENCE, //The calendar entry occurs every day + WEEKLY_RECURRENCE, //The calendar entry occurs every week e.g. every Monday + MONTHLY_RECURRENCE, //The calendar entry occurs every month e.g. every 3rd day of month + YEARLY_RECURRENCE, //The calendar entry occurs every year e.g. every June 1st + WEEKDAY_RECURRENCE, //The calendar entry occurs Mon-Fri every week + MONTHLY_ON_DAY_RECURRENCE, //The calendar entry occurs on the same weekday or weekend every month, e.g., every second Tuesday each month. + INVALID_RECURRENCE = 10000, + UNDEFINED_RECURRENCE /* should be used only to mark a fact filter is not set */ + } EventRecurrence; + + EventRecurrenceRule(); + virtual ~EventRecurrenceRule(); + + EventRecurrence getFrequency() const; + void setFrequency(const EventRecurrence &value); + + int getInterval() const; + void setInterval(const int &value); + + bool isEndDateSet() const; + time_t getEndDate() const; + void setEndDate(time_t value); + void resetEndDate(); + + long getOccurrenceCount() const; + void setOccurrenceCount(long value); + + std::vector getDaysOfTheMonth() const; + void setDaysOfTheMonth(std::vector value); + + std::vector getDaysOfTheWeek() const; + void setDaysOfTheWeek(std::vector value); + + std::vector getDaysOfTheYear() const; + void setDaysOfTheYear(std::vector value); + + std::vector getWeeksOfTheYear() const; + void setWeeksOfTheYear(std::vector value); + + bool getSetPosition() const; + void setSetPosition(bool value); + + std::vector getExceptions() const; + void setExceptions(std::vector value); + + std::string getTimeZone() const; + void setTimeZone(std::string value); + + protected: + EventRecurrence m_frequency; + int m_interval; + DPL::Optional m_endDate; + long m_occurrenceCount; + std::vector m_daysOfTheMonth; + std::vector m_daysOfTheWeek; + std::vector m_daysOfTheYear; + std::vector m_weeksOfTheYear; + bool m_setPosition; + std::vector m_exceptions; + std::string m_timeZone; +}; + +typedef DPL::SharedPtr EventRecurrenceRulePtr; + +} +} +} + +#endif /* _EVENT_RECURRENCE_RULE_H_ */ diff --git a/src/platform/API/Calendar/ICalendar.cpp b/src/platform/API/Calendar/ICalendar.cpp new file mode 100755 index 0000000..22e058f --- /dev/null +++ b/src/platform/API/Calendar/ICalendar.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "ICalendar.h" +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +ICalendar::ICalendar() : + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + m_accountId(0), + m_type(CalendarEvent::EVENT_TYPE) +{ +} + +ICalendar::~ICalendar() +{ +} + +void ICalendar::createEvent(IEventCreateEventPtr &event) +{ + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(event); +} + +void ICalendar::addEvent(IEventAddEventPtr &event) +{ + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(event); +} + +void ICalendar::addEvents(IEventAddEventsPtr &events) +{ + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(events); +} + +void ICalendar::updateEvent(IEventUpdateEventPtr &event) +{ + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(event); +} + +void ICalendar::updateEvents(IEventUpdateEventsPtr &events) +{ + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(events); +} + +void ICalendar::deleteEvent(IEventDeleteEventPtr &event) +{ + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(event); +} + +void ICalendar::deleteEvents(IEventDeleteEventsPtr &events) +{ + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(events); +} + +void ICalendar::findEvents(IEventFindEventsPtr &event) +{ + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(event); +} + +void ICalendar::createEventFromString(IEventCreateEventFromStringPtr &event) +{ + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(event); +} + +void ICalendar::exportEventToString(IEventExportEventToStringPtr &event) +{ + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(event); +} + +void ICalendar::watchChanges(IEventWatchChangesPtr &event) +{ + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(event); +} + +void ICalendar::clearWatch(IEventClearWatchPtr &event) +{ + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(event); +} + +void ICalendar::expandEventRecurrence(IEventExpandEventRecurrencePtr &event) +{ + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(event); +} + +} +} +} diff --git a/src/platform/API/Calendar/ICalendar.h b/src/platform/API/Calendar/ICalendar.h new file mode 100755 index 0000000..1f79e6b --- /dev/null +++ b/src/platform/API/Calendar/ICalendar.h @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_ICALENDAR_H_ +#define _ABSTRACT_LAYER_ICALENDAR_H_ + +#include +#include +#include +#include "CalendarEvent.h" +#include "EventFilter.h" +#include "IEventAddEvent.h" +#include "IEventAddEvents.h" +#include "IEventCreateEvent.h" +#include "IEventDeleteEvent.h" +#include "IEventDeleteEvents.h" +#include "IEventFindEvents.h" +#include "IEventUpdateEvent.h" +#include "IEventUpdateEvents.h" +#include "IEventCreateEventFromString.h" +#include "IEventExportEventToString.h" +#include "IEventWatchChanges.h" +#include "IEventClearWatch.h" +#include "IEventExpandEventRecurrence.h" +#include "OnAddEventsChanged.h" +#include "OnUpdateEventsChanged.h" +#include "OnDeleteEventsChanged.h" +#include "OnEventsChanged.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class ICalendar : public WrtDeviceApis::Commons::EventRequestReceiver< IEventAddEvent >, + public WrtDeviceApis::Commons::EventRequestReceiver< IEventAddEvents >, + public WrtDeviceApis::Commons::EventRequestReceiver< IEventDeleteEvent >, + public WrtDeviceApis::Commons::EventRequestReceiver< IEventDeleteEvents >, + public WrtDeviceApis::Commons::EventRequestReceiver< IEventUpdateEvent >, + public WrtDeviceApis::Commons::EventRequestReceiver< IEventUpdateEvents >, + public WrtDeviceApis::Commons::EventRequestReceiver< IEventFindEvents >, + public WrtDeviceApis::Commons::EventRequestReceiver< IEventCreateEvent >, + public WrtDeviceApis::Commons::EventRequestReceiver< IEventCreateEventFromString >, + public WrtDeviceApis::Commons::EventRequestReceiver< IEventExportEventToString >, + public WrtDeviceApis::Commons::EventRequestReceiver< IEventWatchChanges >, + public WrtDeviceApis::Commons::EventRequestReceiver< IEventClearWatch >, + public WrtDeviceApis::Commons::EventRequestReceiver< IEventExpandEventRecurrence > +{ + public: + ICalendar(); + virtual ~ICalendar(); + virtual void createEvent(IEventCreateEventPtr &event); + virtual void addEvent(IEventAddEventPtr &event); + virtual void addEvents(IEventAddEventsPtr &events); + virtual void updateEvent(IEventUpdateEventPtr &event); + virtual void updateEvents(IEventUpdateEventsPtr &events); + virtual void deleteEvent(IEventDeleteEventPtr &event); + virtual void deleteEvents(IEventDeleteEventsPtr &events); + virtual void findEvents(IEventFindEventsPtr &event); + virtual void createEventFromString(IEventCreateEventFromStringPtr &event); + virtual void exportEventToString(IEventExportEventToStringPtr &event); + virtual void watchChanges(IEventWatchChangesPtr &event); + virtual void clearWatch(IEventClearWatchPtr &event); + virtual void expandEventRecurrence(IEventExpandEventRecurrencePtr &event); + + virtual std::string getName() const + { + return m_name; + } + virtual void setName(const std::string &value) + { + m_name = value; + } + + virtual CalendarEvent::CalendarType getType() const + { + return m_type; + } + virtual void setType(const CalendarEvent::CalendarType value) + { + m_type = value; + } + + virtual std::string getId() const + { + return m_id; + } + virtual void setId(const std::string &value) + { + m_id = value; + } + + virtual int getAccountId() const + { + return m_accountId; + } + virtual void setAccountId(const int value) + { + m_accountId = value; + } + + virtual OnAddEventsChangedEmitterPtr getAddEmitter() const + { + return m_addEmitter; + } + virtual void setAddEmitter(OnAddEventsChangedEmitterPtr value) + { + m_addEmitter = value; + } + + virtual OnUpdateEventsChangedEmitterPtr getUpdateEmitter() const + { + return m_updateEmitter; + } + virtual void setUpdateEmitter(OnUpdateEventsChangedEmitterPtr value) + { + m_updateEmitter = value; + } + + virtual OnDeleteEventsChangedEmitterPtr getDeleteEmitter() const + { + return m_deleteEmitter; + } + virtual void setDeleteEmitter(OnDeleteEventsChangedEmitterPtr value) + { + m_deleteEmitter = value; + } + + virtual std::time_t getLastChangeFetchTime() + { + return m_lastChangeFetchTime; + } + virtual void setLastChangeFetchTime(std::time_t value) + { + m_lastChangeFetchTime = value; + } + + OnEventsChangedEmitters m_changeEmitters; + + protected: + std::string m_id; + int m_accountId; + std::string m_name; + CalendarEvent::CalendarType m_type; + OnAddEventsChangedEmitterPtr m_addEmitter; + OnUpdateEventsChangedEmitterPtr m_updateEmitter; + OnDeleteEventsChangedEmitterPtr m_deleteEmitter; + std::time_t m_lastChangeFetchTime; + + virtual void OnRequestReceived(const IEventAddEventPtr &event) = 0; + virtual void OnRequestReceived(const IEventAddEventsPtr &events) = 0; + virtual void OnRequestReceived(const IEventDeleteEventPtr &event) = 0; + virtual void OnRequestReceived(const IEventDeleteEventsPtr &events) = 0; + virtual void OnRequestReceived(const IEventUpdateEventPtr &event) = 0; + virtual void OnRequestReceived(const IEventUpdateEventsPtr &events) = 0; + virtual void OnRequestReceived(const IEventFindEventsPtr &event) = 0; + virtual void OnRequestReceived(const IEventCreateEventPtr &event) = 0; + virtual void OnRequestReceived(const IEventCreateEventFromStringPtr &event) = 0; + virtual void OnRequestReceived(const IEventExportEventToStringPtr &event) = 0; + virtual void OnRequestReceived(const IEventWatchChangesPtr &event) = 0; + virtual void OnRequestReceived(const IEventClearWatchPtr &event) = 0; + virtual void OnRequestReceived(const IEventExpandEventRecurrencePtr &event) = 0; +}; + +typedef DPL::SharedPtr ICalendarPtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_ICALENDAR_H_ */ diff --git a/src/platform/API/Calendar/ICalendarManager.cpp b/src/platform/API/Calendar/ICalendarManager.cpp new file mode 100755 index 0000000..e56ad7e --- /dev/null +++ b/src/platform/API/Calendar/ICalendarManager.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "ICalendarManager.h" +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +ICalendarManager::ICalendarManager() : + WrtDeviceApis::Commons::EventRequestReceiver< IEventGetCalendars >(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver< IEventGetDefaultCalendar >(WrtDeviceApis::Commons::ThreadEnum::CALENDAR_THREAD) +{ +} + +ICalendarManager::~ICalendarManager() +{ +} + +void ICalendarManager::getCalendars(const IEventGetCalendarsPtr &event) +{ + LogDebug("entered"); + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(event); +} + +void ICalendarManager::getDefaultCalendar(const IEventGetDefaultCalendarPtr &event) +{ + LogDebug("entered"); + WrtDeviceApis::Commons::EventRequestReceiver::PostRequest(event); +} + +} +} +} diff --git a/src/platform/API/Calendar/ICalendarManager.h b/src/platform/API/Calendar/ICalendarManager.h new file mode 100755 index 0000000..1fdfb1f --- /dev/null +++ b/src/platform/API/Calendar/ICalendarManager.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_ICALENDAR_MANAGER_H_ +#define _ABSTRACT_LAYER_ICALENDAR_MANAGER_H_ + +#include "ICalendar.h" +#include "IEventGetCalendars.h" +#include "IEventGetDefaultCalendar.h" +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class ICalendarManager : public WrtDeviceApis::Commons::EventRequestReceiver< IEventGetCalendars >, + public WrtDeviceApis::Commons::EventRequestReceiver< IEventGetDefaultCalendar > +{ + public: + ICalendarManager(); + virtual ~ICalendarManager(); + virtual void getCalendars(const IEventGetCalendarsPtr &event); + virtual void getDefaultCalendar(const IEventGetDefaultCalendarPtr &event); + protected: + virtual void OnRequestReceived(const IEventGetCalendarsPtr &event) = 0; + virtual void OnRequestReceived(const IEventGetDefaultCalendarPtr &event) = 0; +}; + +typedef DPL::SharedPtr ICalendarManagerPtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_ICALENDAR_MANAGER_H_ */ diff --git a/src/platform/API/Calendar/IEventAddEvent.h b/src/platform/API/Calendar/IEventAddEvent.h new file mode 100755 index 0000000..8b35b52 --- /dev/null +++ b/src/platform/API/Calendar/IEventAddEvent.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_IEVENT_ADD_EVENT_H_ +#define _ABSTRACT_LAYER_IEVENT_ADD_EVENT_H_ + +#include +#include "CalendarEvent.h" +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventAddEvent : public WrtDeviceApis::Commons::IEvent +{ + CalendarEventPtr m_eventAdd; + bool m_result; + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + void setEvent(CalendarEventPtr value) + { + m_eventAdd = value; + } + CalendarEventPtr getEvent() const + { + return m_eventAdd; + } + IEventAddEvent() : m_eventAdd(NULL), + m_result(false) + { + LogDebug("entered"); + } + ~IEventAddEvent() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventAddEventPtr; + +} +} +} +#endif /* _ABSTRACT_LAYER_IEVENT_ADD_EVENT_H_ */ diff --git a/src/platform/API/Calendar/IEventAddEvents.h b/src/platform/API/Calendar/IEventAddEvents.h new file mode 100755 index 0000000..a196407 --- /dev/null +++ b/src/platform/API/Calendar/IEventAddEvents.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _IEVENT_ADD_EVENTS_H_ +#define _IEVENT_ADD_EVENTS_H_ + +#include +#include "CalendarEvent.h" +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventAddEvents : public WrtDeviceApis::Commons::IEvent +{ + CalendarEventListPtr m_events; + bool m_result; + + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + void setEvents(CalendarEventListPtr value) + { + m_events = value; + } + CalendarEventListPtr getEvents() const + { + return m_events; + } + + IEventAddEvents() : m_result(false) + { + LogDebug("entered"); + } + ~IEventAddEvents() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventAddEventsPtr; + +} +} +} +#endif /* _IEVENT_ADD_EVENTS_H_ */ diff --git a/src/platform/API/Calendar/IEventClearWatch.h b/src/platform/API/Calendar/IEventClearWatch.h new file mode 100755 index 0000000..50bbe16 --- /dev/null +++ b/src/platform/API/Calendar/IEventClearWatch.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _IEVENT_CLEAR_WATCH_H_ +#define _IEVENT_CLEAR_WATCH_H_ + +#include +#include +#include "CalendarEvent.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventClearWatch : public WrtDeviceApis::Commons::IEvent +{ + long m_watchId; + bool m_result; + + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + void setWatchId(long value) + { + m_watchId = value; + } + long getWatchId() const + { + return m_watchId; + } + + IEventClearWatch() : m_result(false) + { + } + ~IEventClearWatch() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventClearWatchPtr; + +} +} +} +#endif /* _IEVENT_CLEAR_WATCH_H_ */ diff --git a/src/platform/API/Calendar/IEventCreateEvent.h b/src/platform/API/Calendar/IEventCreateEvent.h new file mode 100755 index 0000000..3d82ac3 --- /dev/null +++ b/src/platform/API/Calendar/IEventCreateEvent.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_IEVENT_CREATE_EVENT_H_ +#define _ABSTRACT_LAYER_IEVENT_CREATE_EVENT_H_ + +#include +#include +#include "CalendarEvent.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventCreateEvent : public WrtDeviceApis::Commons::IEvent +{ + CalendarEventPtr m_event; + bool m_result; + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + void setEvent(CalendarEventPtr value) + { + m_event = value; + } + CalendarEventPtr getEvent() const + { + return m_event; + } + IEventCreateEvent() : m_event(NULL), + m_result(false) + { + } + ~IEventCreateEvent() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventCreateEventPtr; + +} +} +} +#endif /* _ABSTRACT_LAYER_IEVENT_CREATE_EVENT_H_ */ diff --git a/src/platform/API/Calendar/IEventCreateEventFromString.h b/src/platform/API/Calendar/IEventCreateEventFromString.h new file mode 100755 index 0000000..34a3eb8 --- /dev/null +++ b/src/platform/API/Calendar/IEventCreateEventFromString.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _IEVENT_CREATE_EVENT_FROM_STRING_H_ +#define _IEVENT_CREATE_EVENT_FROM_STRING_H_ + +#include +#include +#include "ICalendar.h" +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventCreateEventFromString : public WrtDeviceApis::Commons::IEvent< + IEventCreateEventFromString> +{ + CalendarEventPtr m_event; + std::string m_eventString; + int m_format; + bool m_result; + + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + std::string getEventString() const + { + return m_eventString; + } + void setEventString(std::string value) + { + m_eventString = value; + } + + void setEvent(CalendarEventPtr value) + { + m_event = value; + } + CalendarEventPtr getEvent() const + { + return m_event; + } + + void setFormat(int value) + { + m_format = value; + } + int getFormat() const + { + return m_format; + } + + IEventCreateEventFromString() : m_result(false) + { + } + ~IEventCreateEventFromString() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventCreateEventFromStringPtr; + +} +} +} +#endif /* _IEVENT_CREATE_EVENT_FROM_STRING_H_ */ diff --git a/src/platform/API/Calendar/IEventDeleteEvent.h b/src/platform/API/Calendar/IEventDeleteEvent.h new file mode 100755 index 0000000..eb9383a --- /dev/null +++ b/src/platform/API/Calendar/IEventDeleteEvent.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_IEVENT_DELETE_EVENT_H_ +#define _ABSTRACT_LAYER_IEVENT_DELETE_EVENT_H_ + +#include +#include +#include "EventId.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventDeleteEvent : public WrtDeviceApis::Commons::IEvent +{ + EventIdPtr m_eventId; + bool m_result; + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + void setEventId(EventIdPtr value) + { + m_eventId = value; + } + EventIdPtr getEventId() const + { + return m_eventId; + } + + IEventDeleteEvent() : m_eventId(NULL), + m_result(false) + { + } + ~IEventDeleteEvent() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventDeleteEventPtr; + +} +} +} +#endif /* _ABSTRACT_LAYER_IEVENT_DELETE_EVENT_H_ */ diff --git a/src/platform/API/Calendar/IEventDeleteEvents.h b/src/platform/API/Calendar/IEventDeleteEvents.h new file mode 100755 index 0000000..84bb10e --- /dev/null +++ b/src/platform/API/Calendar/IEventDeleteEvents.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _IEVENT_DELETE_EVENTS_H_ +#define _IEVENT_DELETE_EVENTS_H_ + +#include +#include +#include "EventId.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventDeleteEvents : public WrtDeviceApis::Commons::IEvent +{ + EventIdListPtr m_eventIds; + bool m_result; + + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + void setEventIds(EventIdListPtr value) + { + m_eventIds = value; + } + EventIdListPtr getEventIds() const + { + return m_eventIds; + } + + IEventDeleteEvents() : m_result(false) + { + } + ~IEventDeleteEvents() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventDeleteEventsPtr; + +} +} +} +#endif /* _IEVENT_DELETE_EVENTS_H_ */ diff --git a/src/platform/API/Calendar/IEventExpandEventRecurrence.h b/src/platform/API/Calendar/IEventExpandEventRecurrence.h new file mode 100755 index 0000000..e152c1e --- /dev/null +++ b/src/platform/API/Calendar/IEventExpandEventRecurrence.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _IEVENT_EXPAND_EVENT_RECURRENCE_H_ +#define _IEVENT_EXPAND_EVENT_RECURRENCE_H_ + +#include +#include "CalendarEvent.h" +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventExpandEventRecurrence : public WrtDeviceApis::Commons::IEvent +{ + CalendarEventListPtr m_expandedEventList; //output + bool m_result; // ouput + CalendarEventPtr m_event; // input + std::time_t m_startDate; // input + std::time_t m_endDate; // input + + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + CalendarEventListPtr getExpandedEventList() const + { + return m_expandedEventList; + } + + void setEvent(CalendarEventPtr value) + { + m_event = value; + } + CalendarEventPtr getEvent() const + { + return m_event; + } + + void setStartDate(std::time_t value) + { + m_startDate = value; + } + std::time_t getStartDate() const + { + return m_startDate; + } + + void setEndDate(std::time_t value) + { + m_endDate = value; + } + std::time_t getEndDate() const + { + return m_endDate; + } + + void addExpandedEvent(CalendarEventPtr value) + { + m_expandedEventList->push_back(value); + } + + IEventExpandEventRecurrence() : m_result(false) + { + LogDebug("entered"); + CalendarEventListPtr events(new CalendarEventList()); + m_expandedEventList = events; + } + ~IEventExpandEventRecurrence() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventExpandEventRecurrencePtr; + +} +} +} + +#endif /* _IEVENT_EXPAND_EVENT_RECURRENCE_H_ */ diff --git a/src/platform/API/Calendar/IEventExportEventToString.h b/src/platform/API/Calendar/IEventExportEventToString.h new file mode 100755 index 0000000..ed9d4f5 --- /dev/null +++ b/src/platform/API/Calendar/IEventExportEventToString.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _IEVENT_EXPORT_EVENT_TO_STRING_H_ +#define _IEVENT_EXPORT_EVENT_TO_STRING_H_ + +#include +#include +#include "CalendarEvent.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventExportEventToString : public WrtDeviceApis::Commons::IEvent +{ + std::string m_eventString; + CalendarEventPtr m_event; + int m_format; + bool m_result; + + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + void setEvent(CalendarEventPtr value) + { + m_event = value; + } + CalendarEventPtr getEvent() const + { + return m_event; + } + + void setEventString(std::string value) + { + m_eventString = value; + } + std::string getEventString() const + { + return m_eventString; + } + + void setFormat(int value) + { + m_format = value; + } + int getFormat() const + { + return m_format; + } + + IEventExportEventToString() : m_result(false) + { + } + ~IEventExportEventToString() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventExportEventToStringPtr; + +} +} +} +#endif /* _IEVENT_EXPORT_EVENT_TO_STRING_H_ */ diff --git a/src/platform/API/Calendar/IEventFindEvents.h b/src/platform/API/Calendar/IEventFindEvents.h new file mode 100755 index 0000000..26ecea8 --- /dev/null +++ b/src/platform/API/Calendar/IEventFindEvents.h @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_IEVENT_FIND_EVENTS_H_ +#define _ABSTRACT_LAYER_IEVENT_FIND_EVENTS_H_ + +#include +#include +#include "CalendarEvent.h" +#include "EventFilter.h" +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventFindEvents : public WrtDeviceApis::Commons::IEvent +{ + /* user is responsible to free objects inside list */ + CalendarEventListPtr m_events; + bool m_result; + EventFilterPtr m_filter; + + /* generic filter parameters */ + Tizen::FilterPtr m_genericFilter; + Tizen::SortModeArrayPtr m_sortModes; + std::vector m_attributesOfInterest; + bool m_genericFilterIsSet; + bool m_sortModesIsSet; + bool m_attributesOfInterestIsSet; + + public: + void setFilter(EventFilterPtr value) + { + m_filter = value; + } + EventFilterPtr getFilter() const + { + return m_filter; + } + + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + void addEvent(CalendarEventPtr value) + { + m_events->push_back(value); + } + + CalendarEventListPtr getEvents() + { + return m_events; + } + + Tizen::FilterPtr getGenericFilter() const + { + return m_genericFilter; + } + + void setGenericFilter(const Tizen::FilterPtr &value) + { + m_genericFilter = value; + m_genericFilterIsSet = true; + } + + Tizen::SortModeArrayPtr getSortModes() const + { + return m_sortModes; + } + + void setSortModes(const Tizen::SortModeArrayPtr &value) + { + m_sortModes = value; + m_sortModesIsSet = true; + } + + std::vector getAttributesOfInterest() const + { + return m_attributesOfInterest; + } + + void setAttributesOfInterest(const std::vector &value) + { + m_attributesOfInterest = value; + m_attributesOfInterestIsSet = true; + } + + bool getGenericFilterIsSet() const + { + return m_genericFilterIsSet; + } + + bool getSortModesIsSet() const + { + return m_sortModesIsSet; + } + + bool getAttributesOfInterestIsSet() const + { + return m_attributesOfInterestIsSet; + } + + IEventFindEvents() : m_result(false), + m_genericFilterIsSet(false), + m_sortModesIsSet(false), + m_attributesOfInterestIsSet(false) + { + CalendarEventListPtr events(new CalendarEventList()); + m_events = events; + } + ~IEventFindEvents() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventFindEventsPtr; + +} +} +} +#endif /* _ABSTRACT_LAYER_IEVENT_FIND_EVENTS_H_ */ diff --git a/src/platform/API/Calendar/IEventGetCalendars.h b/src/platform/API/Calendar/IEventGetCalendars.h new file mode 100755 index 0000000..d1f2fe9 --- /dev/null +++ b/src/platform/API/Calendar/IEventGetCalendars.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_IEVENT_GET_CALENDARS_H_ +#define _ABSTRACT_LAYER_IEVENT_GET_CALENDARS_H_ + +#include +#include +#include "ICalendar.h" +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventGetCalendars : public WrtDeviceApis::Commons::IEvent< + IEventGetCalendars> +{ + std::vector m_calendars; + bool m_result; + CalendarEvent::CalendarType m_type; + + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + void setType(CalendarEvent::CalendarType value) + { + m_type = value; + } + CalendarEvent::CalendarType getType() const + { + return m_type; + } + + void addCalendar(ICalendarPtr value) + { + m_calendars.push_back(value); + } + std::vector getCalendars() const + { + return m_calendars; + } + IEventGetCalendars() : m_result(false) + { + } + ~IEventGetCalendars() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventGetCalendarsPtr; + +} +} +} +#endif /* _ABSTRACT_LAYER_IEVENT_UPDATE_EVENT_H_ */ diff --git a/src/platform/API/Calendar/IEventGetDefaultCalendar.h b/src/platform/API/Calendar/IEventGetDefaultCalendar.h new file mode 100755 index 0000000..862e1ce --- /dev/null +++ b/src/platform/API/Calendar/IEventGetDefaultCalendar.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_IEVENT_GET_DEFAULT_CALENDAR_H_ +#define _ABSTRACT_LAYER_IEVENT_GET_DEFAULT_CALENDAR_H_ + +#include +#include +#include "ICalendar.h" +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventGetDefaultCalendar : public WrtDeviceApis::Commons::IEvent< + IEventGetDefaultCalendar> +{ + ICalendarPtr m_calendar; + bool m_result; + CalendarEvent::CalendarType m_type; + + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + void setType(CalendarEvent::CalendarType value) + { + m_type = value; + } + CalendarEvent::CalendarType getType() const + { + return m_type; + } + + void setCalendar(ICalendarPtr value) + { + m_calendar = value; + } + ICalendarPtr getCalendar() const + { + return m_calendar; + } + + IEventGetDefaultCalendar() : m_result(false) + { + } + ~IEventGetDefaultCalendar() + { + } + + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventGetDefaultCalendarPtr; + +} +} +} +#endif /* _ABSTRACT_LAYER_IEVENT_GET_DEFAULT_CALENDAR_H_ */ diff --git a/src/platform/API/Calendar/IEventUpdateEvent.h b/src/platform/API/Calendar/IEventUpdateEvent.h new file mode 100755 index 0000000..906be23 --- /dev/null +++ b/src/platform/API/Calendar/IEventUpdateEvent.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_IEVENT_UPDATE_EVENT_H_ +#define _ABSTRACT_LAYER_IEVENT_UPDATE_EVENT_H_ + +#include +#include "CalendarEvent.h" +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventUpdateEvent : public WrtDeviceApis::Commons::IEvent +{ + CalendarEventPtr m_event; + bool m_result; + bool m_updateAllInstances; + + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + void setEvent(CalendarEventPtr value) + { + m_event = value; + } + CalendarEventPtr getEvent() const + { + return m_event; + } + + void setUpdateAllInstances(bool value) + { + m_updateAllInstances = value; + } + bool getUpdateAllInstances() const + { + return m_updateAllInstances; + } + + IEventUpdateEvent() : m_event(NULL), + m_result(false), m_updateAllInstances(true) + { + } + ~IEventUpdateEvent() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventUpdateEventPtr; + +} +} +} +#endif /* _ABSTRACT_LAYER_IEVENT_UPDATE_EVENT_H_ */ diff --git a/src/platform/API/Calendar/IEventUpdateEvents.h b/src/platform/API/Calendar/IEventUpdateEvents.h new file mode 100755 index 0000000..bb927f6 --- /dev/null +++ b/src/platform/API/Calendar/IEventUpdateEvents.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _IEVENT_UPDATE_EVENTS_H_ +#define _IEVENT_UPDATE_EVENTS_H_ + +#include +#include "CalendarEvent.h" +#include + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventUpdateEvents : public WrtDeviceApis::Commons::IEvent +{ + CalendarEventListPtr m_events; + bool m_result; + bool m_updateAllInstances; + + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + void setEvents(CalendarEventListPtr value) + { + m_events = value; + } + CalendarEventListPtr getEvents() const + { + return m_events; + } + + void setUpdateAllInstances(bool value) + { + m_updateAllInstances = value; + } + bool getUpdateAllInstances() const + { + return m_updateAllInstances; + } + + IEventUpdateEvents() : m_result(false), m_updateAllInstances(true) + { + } + ~IEventUpdateEvents() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventUpdateEventsPtr; + +} +} +} +#endif /* _IEVENT_UPDATE_EVENTS_H_ */ diff --git a/src/platform/API/Calendar/IEventWatchChanges.h b/src/platform/API/Calendar/IEventWatchChanges.h new file mode 100755 index 0000000..8c612d5 --- /dev/null +++ b/src/platform/API/Calendar/IEventWatchChanges.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _IEVENT_WATCH_CHANGES_H_ +#define _IEVENT_WATCH_CHANGES_H_ + +#include +#include +#include "CalendarEvent.h" +#include "OnEventsChanged.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class IEventWatchChanges : public WrtDeviceApis::Commons::IEvent +{ + AttributeListPtr m_attributesOfInterest; + bool m_result; + long m_watchId; + OnEventsChangedEmitterPtr m_emitter; + + public: + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + void setAttributes(AttributeListPtr value) + { + m_attributesOfInterest = value; + } + AttributeListPtr getAttributes() const + { + return m_attributesOfInterest; + } + + void setWatchId(long value) + { + m_watchId = value; + } + long getWatchId() const + { + return m_watchId; + } + + void setEmitter(OnEventsChangedEmitterPtr value) + { + m_emitter = value; + } + OnEventsChangedEmitterPtr getEmitter() const + { + return m_emitter; + } + + IEventWatchChanges() : m_result(false) + { + } + ~IEventWatchChanges() + { + } + virtual void clearOnCancel() + { + } +}; + +typedef DPL::SharedPtr IEventWatchChangesPtr; + +} +} +} +#endif /* _IEVENT_WATCH_CHANGES_H_ */ diff --git a/src/platform/API/Calendar/OnAddEventsChanged.h b/src/platform/API/Calendar/OnAddEventsChanged.h new file mode 100755 index 0000000..f634499 --- /dev/null +++ b/src/platform/API/Calendar/OnAddEventsChanged.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ON_ADD_EVENTS_CHANGED_H_ +#define _ON_ADD_EVENTS_CHANGED_H_ + +#include +#include +#include +#include +#include +#include "CalendarEvent.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class OnAddEventsChanged : public WrtDeviceApis::Commons::ListenerEvent +{ + public: + typedef enum + { + SUCCESS_ALL, + FAIL_ALL, + EVENT_ADD_SUCCESS, + EVENT_ADD_FAIL + } EventAddStatus; + + void setResult (bool value) { + m_result = value; + } + bool getResult() const { + return m_result; + } + + void setEvent(CalendarEventPtr value) { + m_event = value; + } + CalendarEventPtr getEvent() const { + return m_event; + } + + void setStatus(EventAddStatus value) { + m_status = value; + } + EventAddStatus getStatus() const { + return m_status; + } + + OnAddEventsChanged() : m_result(false) { + } + ~OnAddEventsChanged() { + } + + private: + CalendarEventPtr m_event; + EventAddStatus m_status; + bool m_result; +}; + +typedef DPL::SharedPtr OnAddEventsChangedPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter OnAddEventsChangedEmitter; +typedef DPL::SharedPtr OnAddEventsChangedEmitterPtr; + +} +} +} + +#endif //_ON_ADD_EVENTS_CHANGED_H_ diff --git a/src/platform/API/Calendar/OnDeleteEventsChanged.h b/src/platform/API/Calendar/OnDeleteEventsChanged.h new file mode 100755 index 0000000..f639642 --- /dev/null +++ b/src/platform/API/Calendar/OnDeleteEventsChanged.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ON_DELETE_EVENTS_CHANGED_H_ +#define _ON_DELETE_EVENTS_CHANGED_H_ + +#include +#include +#include +#include +#include +#include "EventId.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class OnDeleteEventsChanged : public WrtDeviceApis::Commons::ListenerEvent +{ + public: + typedef enum + { + SUCCESS_ALL, + FAIL_ALL, + EVENT_DELETE_SUCCESS, + EVENT_DELETE_FAIL + } EventDeleteStatus; + + void setResult (bool value) { + m_result = value; + } + bool getResult() const { + return m_result; + } + + void setEventId(EventIdPtr value) { + m_eventId = value; + } + EventIdPtr getEventId() const { + return m_eventId; + } + + void setStatus(EventDeleteStatus value) { + m_status = value; + } + EventDeleteStatus getStatus() const { + return m_status; + } + + OnDeleteEventsChanged() : m_result(false) { + } + ~OnDeleteEventsChanged() { + } + + private: + EventIdPtr m_eventId; + EventDeleteStatus m_status; + bool m_result; +}; + +typedef DPL::SharedPtr OnDeleteEventsChangedPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter OnDeleteEventsChangedEmitter; +typedef DPL::SharedPtr OnDeleteEventsChangedEmitterPtr; + +} +} +} + +#endif //_ON_DELETE_EVENTS_CHANGED_H_ diff --git a/src/platform/API/Calendar/OnEventsChanged.h b/src/platform/API/Calendar/OnEventsChanged.h new file mode 100755 index 0000000..5435fd3 --- /dev/null +++ b/src/platform/API/Calendar/OnEventsChanged.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ON_EVENTS_CHANGED_H_ +#define _ON_EVENTS_CHANGED_H_ + +#include +#include +#include +#include +#include +#include "CalendarEvent.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class OnEventsChanged : public WrtDeviceApis::Commons::ListenerEvent +{ + public: + typedef enum + { + ON_ADD, + ON_UPDATE, + ON_DELETE, + //ON_CALENDAR_RESET + } EventChangeStatus; + + void setResult (bool value) { + m_result = value; + } + bool getResult() const { + return m_result; + } + + CalendarEventListPtr getEventList() const { + return m_eventList; + } + + void setStatus(EventChangeStatus value) { + m_status = value; + } + EventChangeStatus getStatus() const { + return m_status; + } + + void addEvent(CalendarEventPtr value) { + m_eventList->push_back(value); + } + + OnEventsChanged() : m_result(false) { + CalendarEventListPtr events(new CalendarEventList()); + m_eventList = events; + } + ~OnEventsChanged() { + } + + private: + CalendarEventListPtr m_eventList; + EventChangeStatus m_status; + bool m_result; +}; + +typedef DPL::SharedPtr OnEventsChangedPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter OnEventsChangedEmitter; +typedef DPL::SharedPtr OnEventsChangedEmitterPtr; +typedef WrtDeviceApis::Commons::Emitters OnEventsChangedEmitters; + +} +} +} + +#endif //_ON_EVENTS_CHANGED_H_ diff --git a/src/platform/API/Calendar/OnUpdateEventsChanged.h b/src/platform/API/Calendar/OnUpdateEventsChanged.h new file mode 100755 index 0000000..855f94f --- /dev/null +++ b/src/platform/API/Calendar/OnUpdateEventsChanged.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ON_UPDATE_EVENTS_CHANGED_H_ +#define _ON_UPDATE_EVENTS_CHANGED_H_ + +#include +#include +#include +#include +#include +#include "CalendarEvent.h" + +namespace TizenApis { +namespace Api { +namespace Calendar { + +class OnUpdateEventsChanged : public WrtDeviceApis::Commons::ListenerEvent +{ + public: + typedef enum + { + SUCCESS_ALL, + FAIL_ALL, + EVENT_UPDATE_SUCCESS, + EVENT_UPDATE_FAIL + } EventUpdateStatus; + + void setResult (bool value) { + m_result = value; + } + bool getResult() const { + return m_result; + } + + void setEvent(CalendarEventPtr value) { + m_event = value; + } + CalendarEventPtr getEvent() const { + return m_event; + } + + void setStatus(EventUpdateStatus value) { + m_status = value; + } + EventUpdateStatus getStatus() const { + return m_status; + } + + OnUpdateEventsChanged() : m_result(false) { + } + ~OnUpdateEventsChanged() { + } + + private: + CalendarEventPtr m_event; + EventUpdateStatus m_status; + bool m_result; +}; + +typedef DPL::SharedPtr OnUpdateEventsChangedPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter OnUpdateEventsChangedEmitter; +typedef DPL::SharedPtr OnUpdateEventsChangedEmitterPtr; + +} +} +} + +#endif //_ON_UPDATE_EVENTS_CHANGED_H_ diff --git a/src/platform/API/Calendar/config.cmake b/src/platform/API/Calendar/config.cmake new file mode 100755 index 0000000..f6c6bb3 --- /dev/null +++ b/src/platform/API/Calendar/config.cmake @@ -0,0 +1,13 @@ +get_current_path() +set(SRCS_PLATFORM_API_CALENDAR + ${CURRENT_PATH}/CalendarEvent.cpp + ${CURRENT_PATH}/CalendarFactory.cpp + ${CURRENT_PATH}/EventFilter.cpp + ${CURRENT_PATH}/ICalendar.cpp + ${CURRENT_PATH}/ICalendarManager.cpp + ${CURRENT_PATH}/EventAttendee.cpp + ${CURRENT_PATH}/EventRecurrenceRule.cpp + ${CURRENT_PATH}/EventId.cpp + ${CURRENT_PATH}/EventAlarm.cpp + PARENT_SCOPE +) \ No newline at end of file diff --git a/src/platform/API/Call/CallHistoryEntryProperties.cpp b/src/platform/API/Call/CallHistoryEntryProperties.cpp new file mode 100755 index 0000000..bb5437a --- /dev/null +++ b/src/platform/API/Call/CallHistoryEntryProperties.cpp @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "CallHistoryEntryProperties.h" + +namespace TizenApis { +namespace Api { +namespace Call { +CallHistoryEntryProperties::CallHistoryEntryProperties() : + m_entryId(0), + m_accountId(""), + m_callType(""), + m_remoteParty(""), + m_contactId(""), + m_contactDetails(""), + m_forwardedFrom(""), + m_startTime(0), + m_duration(0), + m_endReason(""), + m_kind(""), + m_direction(""), + m_cost(0), + m_currency(""), + m_filterMark(false) +{ + m_usedCapabilities = stringArrayPtr(new stringArray()); + m_recording = stringArrayPtr(new stringArray()); +} + +void CallHistoryEntryProperties::setEntryId(const unsigned long EntryId) +{ + m_entryId = EntryId; +} + +void CallHistoryEntryProperties::setAccountId(const std::string AccountId) +{ + m_accountId = AccountId; +} + +void CallHistoryEntryProperties::setCallType(const std::string CallType) +{ + m_callType = CallType; +} + +void CallHistoryEntryProperties::setRemoteParty(const std::string RemoteParty) +{ + m_remoteParty = RemoteParty; +} + +void CallHistoryEntryProperties::setContactId(const std::string ContactId) +{ + m_contactId = ContactId; +} + +void CallHistoryEntryProperties::setContactDetails(const std::string ContactDetails) +{ + m_contactDetails = ContactDetails; +} + +void CallHistoryEntryProperties::setForwardedFrom(const std::string ForwardedFrom) +{ + m_forwardedFrom = ForwardedFrom; +} + +void CallHistoryEntryProperties::setStartTime(const time_t StartTime) +{ + m_startTime = StartTime; +} + +void CallHistoryEntryProperties::setDuration(const unsigned long Duration) +{ + m_duration = Duration; +} + +void CallHistoryEntryProperties::setEndReason(const std::string EndReason) +{ + m_endReason = EndReason; +} + +void CallHistoryEntryProperties::setUsedCapabilities(const stringArrayPtr &UsedCapabilities) +{ + m_usedCapabilities = UsedCapabilities; +} + +void CallHistoryEntryProperties::setKind(const std::string Kind) +{ + m_kind = Kind; +} + +void CallHistoryEntryProperties::setDirection(const std::string Direction) +{ + m_direction = Direction; +} + +void CallHistoryEntryProperties::setRecording(const stringArrayPtr &Recording) +{ + m_recording = Recording; +} + +void CallHistoryEntryProperties::setCost(const unsigned long Cost) +{ + m_cost = Cost; +} + +void CallHistoryEntryProperties::setCurrency(const std::string Currency) +{ + m_currency = Currency; +} + + +void CallHistoryEntryProperties::setFilterMark(const bool Mark) +{ + m_filterMark = Mark; +} + +unsigned long CallHistoryEntryProperties::getEntryId() const +{ + return m_entryId; +} + +std::string CallHistoryEntryProperties::getAccountId() const +{ + return m_accountId; +} + +std::string CallHistoryEntryProperties::getCallType() const +{ + return m_callType; +} + +std::string CallHistoryEntryProperties::getRemoteParty() const +{ + return m_remoteParty; +} + +std::string CallHistoryEntryProperties::getContactId() const +{ + return m_contactId; +} + +std::string CallHistoryEntryProperties::getContactDetails() const +{ + return m_contactDetails; +} + +std::string CallHistoryEntryProperties::getForwardedFrom() const +{ + return m_forwardedFrom; +} + +time_t CallHistoryEntryProperties::getStartTime() const +{ + return m_startTime; +} + +unsigned long CallHistoryEntryProperties::getDuration() const +{ + return m_duration; +} + +std::string CallHistoryEntryProperties::getEndReason() const +{ + return m_endReason; +} + +stringArrayPtr CallHistoryEntryProperties::getUsedCapabilities() const +{ + return m_usedCapabilities; +} + +std::string CallHistoryEntryProperties::getKind() const +{ + return m_kind; +} + +std::string CallHistoryEntryProperties::getDirection() const +{ + return m_direction; +} + +stringArrayPtr CallHistoryEntryProperties::getRecording() const +{ + return m_recording; +} + +unsigned long CallHistoryEntryProperties::getCost() const +{ + return m_cost; +} + +std::string CallHistoryEntryProperties::getCurrency() const +{ + return m_currency; +} + +bool CallHistoryEntryProperties::getFilterMark() const +{ + return m_filterMark; +} + +} +} +} diff --git a/src/platform/API/Call/CallHistoryEntryProperties.h b/src/platform/API/Call/CallHistoryEntryProperties.h new file mode 100755 index 0000000..5c623a7 --- /dev/null +++ b/src/platform/API/Call/CallHistoryEntryProperties.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_API_CALLHISTORY_ENTRY_PROPERTIES_H_ +#define TIZENAPIS_API_CALLHISTORY_ENTRY_PROPERTIES_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Call { +class CallHistoryEntryProperties; +typedef DPL::SharedPtr CallHistoryEntryPropertiesPtr; +typedef std::vector CallHistoryEntryList; +typedef DPL::SharedPtr CallHistoryEntryListPtr; +typedef std::vector stringArray; +typedef DPL::SharedPtr stringArrayPtr; + +class CallHistoryEntryProperties +{ +private: + unsigned long m_entryId; + std::string m_accountId; + std::string m_callType; + std::string m_remoteParty; + std::string m_contactId; + std::string m_contactDetails; + std::string m_forwardedFrom; + time_t m_startTime; + unsigned long m_duration; + std::string m_endReason; + stringArrayPtr m_usedCapabilities; + std::string m_kind; + std::string m_direction; + stringArrayPtr m_recording; + unsigned long m_cost; + std::string m_currency; + + bool m_filterMark; + +public: + void setEntryId(const unsigned long EntryId); + void setAccountId(const std::string AccountId); + void setCallType(const std::string CallType); + void setRemoteParty(const std::string RemoteParty); + void setContactId(const std::string ContactId); + void setContactDetails(const std::string ContactDetails); + void setForwardedFrom(const std::string ForwardedFrom); + void setStartTime(const time_t StartTime); + void setDuration(const unsigned long Duration); + void setEndReason(const std::string EndReason); + void setUsedCapabilities(const stringArrayPtr &UsedCapabilities); + void setKind(const std::string Kind); + void setDirection(const std::string Direction); + void setRecording(const stringArrayPtr &Recording); + void setCost(const unsigned long Cost); + void setCurrency(const std::string Currency); + void setFilterMark(const bool mark); + + unsigned long getEntryId() const; + std::string getAccountId() const; + std::string getCallType() const; + std::string getRemoteParty() const; + std::string getContactId() const; + std::string getContactDetails() const; + std::string getForwardedFrom() const; + time_t getStartTime() const; + unsigned long getDuration() const; + std::string getEndReason() const; + stringArrayPtr getUsedCapabilities() const; + std::string getKind() const; + std::string getDirection() const; + stringArrayPtr getRecording() const; + unsigned long getCost() const; + std::string getCurrency() const; + bool getFilterMark() const; + + CallHistoryEntryProperties(); +}; +} +} +} + +#endif \ No newline at end of file diff --git a/src/platform/API/Call/CallHistoryFactory.cpp b/src/platform/API/Call/CallHistoryFactory.cpp new file mode 100755 index 0000000..06f4932 --- /dev/null +++ b/src/platform/API/Call/CallHistoryFactory.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include "CallHistoryFactory.h" + +namespace TizenApis { +namespace Api { +namespace Call { +CallHistoryFactory& CallHistoryFactory::getInstance() +{ + static CallHistoryFactory theInstance; + return theInstance; +} + +ICallHistoryPtr CallHistoryFactory::getCallHistoryObject() +{ + ICallHistoryPtr result(new Platform::Call::CallHistory()); + return result; +} +CallHistoryFactory::CallHistoryFactory() +{ +} + +} +} +} + diff --git a/src/platform/API/Call/CallHistoryFactory.h b/src/platform/API/Call/CallHistoryFactory.h new file mode 100755 index 0000000..6190a98 --- /dev/null +++ b/src/platform/API/Call/CallHistoryFactory.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_CALLHISTORY_FACTORY_H_ +#define _ABSTRACT_LAYER_CALLHISTORY_FACTORY_H_ + +#include +#include "ICallHistory.h" + +namespace TizenApis { +namespace Api { +namespace Call { + +class CallHistoryFactory : public DPL::Noncopyable +{ +public: + + static CallHistoryFactory& getInstance(); + ICallHistoryPtr getCallHistoryObject(); + +protected: + CallHistoryFactory(); +}; + +} +} +} + +#endif \ No newline at end of file diff --git a/src/platform/API/Call/EventFindCallHistory.cpp b/src/platform/API/Call/EventFindCallHistory.cpp new file mode 100755 index 0000000..01838a0 --- /dev/null +++ b/src/platform/API/Call/EventFindCallHistory.cpp @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "EventFindCallHistory.h" + +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { +namespace Api { +namespace Call { +EventFindCallHistory::EventFindCallHistory() : m_filterIsSet(false), + m_sortModesIsSet(false), + m_limitIsSet(false), + m_offsetIsSet(false) +{ +} + +void EventFindCallHistory::setFilter(const FilterPtr &filter) +{ + m_filter = filter; + m_filterIsSet = true; +} + +void EventFindCallHistory::setSortMode(const SortModeArrayPtr &sortMode) +{ + m_sortModes = sortMode; + m_sortModesIsSet = true; +} + +void EventFindCallHistory::setLimit(const unsigned long limit) +{ + if (limit > 0) { + m_limit = limit; + m_limitIsSet = true; + } +} + +void EventFindCallHistory::setOffset(const unsigned long offset) +{ + if (offset > 0) { + m_offset = offset; + m_offsetIsSet = true; + } +} + +void EventFindCallHistory::setResult(const CallHistoryEntryListPtr &callEntries) +{ + m_callEntries = callEntries; +} + +FilterPtr EventFindCallHistory::getFilter() const +{ + return m_filter; +} + +SortModeArrayPtr EventFindCallHistory::getSortMode() const +{ + return m_sortModes; +} + +unsigned long EventFindCallHistory::getLimit() const +{ + return m_limit; +} + +unsigned long EventFindCallHistory::getOffset() const +{ + return m_offset; +} + +bool EventFindCallHistory::getFilterIsSet() const +{ + return m_filterIsSet; +} + +bool EventFindCallHistory::getSortModesIsSet() const +{ + return m_sortModesIsSet; +} + +bool EventFindCallHistory::getLimitIsSet() const +{ + return m_limitIsSet; +} + +bool EventFindCallHistory::getOffsetIsSet() const +{ + return m_offsetIsSet; +} + +CallHistoryEntryListPtr EventFindCallHistory::getResult() const +{ + return m_callEntries; +} + +} +} +} \ No newline at end of file diff --git a/src/platform/API/Call/EventFindCallHistory.h b/src/platform/API/Call/EventFindCallHistory.h new file mode 100755 index 0000000..25327c6 --- /dev/null +++ b/src/platform/API/Call/EventFindCallHistory.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_API_CALL_EVENT_FIND_CALLHISTORY_H_ +#define TIZENAPIS_API_CALL_EVENT_FIND_CALLHISTORY_H_ + +#include +#include +#include +#include +#include +#include "CallHistoryEntryProperties.h" + +namespace TizenApis { +namespace Api { +namespace Call { +class EventFindCallHistory : public WrtDeviceApis::Commons::IEvent +{ + private: + CallHistoryEntryListPtr m_callEntries; + Tizen::FilterPtr m_filter; + Tizen::SortModeArrayPtr m_sortModes; + unsigned long m_limit; + unsigned long m_offset; + bool m_filterIsSet; + bool m_sortModesIsSet; + bool m_limitIsSet; + bool m_offsetIsSet; + + public: + void setFilter(const Tizen::FilterPtr &filter); + void setSortMode(const Tizen::SortModeArrayPtr &sortMode); + void setLimit(const unsigned long limit); + void setOffset(const unsigned long offset); + void setResult(const CallHistoryEntryListPtr &callEntries); + + Tizen::FilterPtr getFilter() const; + Tizen::SortModeArrayPtr getSortMode() const; + unsigned long getLimit() const; + unsigned long getOffset() const; + bool getFilterIsSet() const; + bool getSortModesIsSet() const; + bool getLimitIsSet() const; + bool getOffsetIsSet() const; + CallHistoryEntryListPtr getResult() const; + + EventFindCallHistory(); +}; + +typedef DPL::SharedPtr EventFindCallHistoryPtr; +} +} +} + +#endif \ No newline at end of file diff --git a/src/platform/API/Call/EventRemoveBatch.cpp b/src/platform/API/Call/EventRemoveBatch.cpp new file mode 100755 index 0000000..f2d2b5c --- /dev/null +++ b/src/platform/API/Call/EventRemoveBatch.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "EventRemoveBatch.h" + +namespace TizenApis { +namespace Api { +namespace Call { +EventRemoveBatch::EventRemoveBatch() +{ +} + +void EventRemoveBatch::setEntryIds(const std::vector &entryIds) +{ + m_entryIds = entryIds; +} + +std::vector EventRemoveBatch::getEntryIds() const +{ + return m_entryIds; +} + +} +} +} \ No newline at end of file diff --git a/src/platform/API/Call/EventRemoveBatch.h b/src/platform/API/Call/EventRemoveBatch.h new file mode 100755 index 0000000..b1c6188 --- /dev/null +++ b/src/platform/API/Call/EventRemoveBatch.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_API_CALL_EVENT_REMOVE_BATCH_H_ +#define TIZENAPIS_API_CALL_EVENT_REMOVE_BATCH_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Call { +class EventRemoveBatch : public WrtDeviceApis::Commons::IEvent +{ + private: + std::vector m_entryIds; + + public: + void setEntryIds(const std::vector &entryIds); + std::vector getEntryIds() const; + + EventRemoveBatch(); +}; + +typedef DPL::SharedPtr EventRemoveBatchPtr; +} +} +} + +#endif \ No newline at end of file diff --git a/src/platform/API/Call/ICallHistory.cpp b/src/platform/API/Call/ICallHistory.cpp new file mode 100755 index 0000000..48b7550 --- /dev/null +++ b/src/platform/API/Call/ICallHistory.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "ICallHistory.h" + +namespace TizenApis { +namespace Api { +namespace Call { + +using namespace WrtDeviceApis::Commons; + +ICallHistory::ICallHistory() : + EventRequestReceiver(ThreadEnum::CALLHISTORY_THREAD), + EventRequestReceiver(ThreadEnum::CALLHISTORY_THREAD) +{ +} + +ICallHistory::~ICallHistory() +{ +} + +} +} +} diff --git a/src/platform/API/Call/ICallHistory.h b/src/platform/API/Call/ICallHistory.h new file mode 100755 index 0000000..0ec4540 --- /dev/null +++ b/src/platform/API/Call/ICallHistory.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_API_ICALLHISTORY_H_ +#define TIZENAPIS_API_ICALLHISTORY_H_ + +#include +#include +#include "EventFindCallHistory.h" +#include "EventRemoveBatch.h" + +namespace TizenApis { +namespace Api { +namespace Call{ + +class ICallHistory : public WrtDeviceApis::Commons::EventRequestReceiver, + public WrtDeviceApis::Commons::EventRequestReceiver +{ +public: + virtual ~ICallHistory(); + + virtual void find(const EventFindCallHistoryPtr& event) = 0; + + virtual bool remove(const unsigned long entryId) = 0; + + virtual void removeBatch(const EventRemoveBatchPtr& event) = 0; + +protected: + ICallHistory(); + virtual void OnRequestReceived(const EventFindCallHistoryPtr& event) = 0; + virtual void OnRequestReceived(const EventRemoveBatchPtr& event) = 0; +}; +typedef DPL::SharedPtr ICallHistoryPtr; +} +} +} + +#endif diff --git a/src/platform/API/Call/config.cmake b/src/platform/API/Call/config.cmake new file mode 100755 index 0000000..5a991ef --- /dev/null +++ b/src/platform/API/Call/config.cmake @@ -0,0 +1,9 @@ +get_current_path() +set(SRCS_PLATFORM_API_CALL + ${CURRENT_PATH}/ICallHistory.cpp + ${CURRENT_PATH}/CallHistoryFactory.cpp + ${CURRENT_PATH}/EventFindCallHistory.cpp + ${CURRENT_PATH}/EventRemoveBatch.cpp + ${CURRENT_PATH}/CallHistoryEntryProperties.cpp + PARENT_SCOPE +) diff --git a/src/platform/API/Contact/Contact.cpp b/src/platform/API/Contact/Contact.cpp new file mode 100755 index 0000000..3e913ad --- /dev/null +++ b/src/platform/API/Contact/Contact.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Contact.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "Contact.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +Contact::Contact() : + m_readOnly(false), + m_idIsSet(false), + m_readOnlyIsSet(false), + m_lastUpdatedIsSet(false) +{ +} + +Contact::Contact(const ContactProperties &contactProperties) : + ContactProperties(contactProperties), + m_readOnly(false), + m_idIsSet(false), + m_readOnlyIsSet(false), + m_lastUpdatedIsSet(false) +{ +} + +Contact::~Contact() +{ +} + +std::string Contact::getId() const +{ + return m_id; +} + +void Contact::setId(const std::string value) +{ + m_id = value; + m_idIsSet = true; +} + +bool Contact::getIdIsSet() const +{ + return m_idIsSet; +} + +void Contact::setId(const int value) +{ + std::stringstream oss; + oss << value; + m_id = oss.str(); + m_idIsSet = true; +} + +bool Contact::getReadOnly() const +{ + return m_readOnly; +} + +void Contact::setReadOnly(const bool &value) +{ + m_readOnly = value; + m_readOnlyIsSet = true; +} + +bool Contact::getReadOnlyIsSet() const +{ + return m_readOnlyIsSet; +} + +std::tm Contact::getLastUpdated() const +{ + return m_lastUpdated; +} + +void Contact::setLastUpdated(const std::tm &value) +{ + m_lastUpdated = value; + m_lastUpdatedIsSet = true; +} + +bool Contact::getLastUpdatedIsSet() const +{ + return m_lastUpdatedIsSet; +} + +void Contact::clear() +{ + LogDebug("entered"); + //clear all fields + ContactProperties::clear(); + m_id.clear(); + m_readOnly = false; + m_idIsSet = false; + m_readOnlyIsSet = false; +} + +ContactPtr Contact::clone() +{ + // TODO + //clone object + //use defaul copy constructor + ContactPtr result(new Contact(*this)); + return result; +} + +} // Contact +} // Api +} // TizenApis diff --git a/src/platform/API/Contact/Contact.h b/src/platform/API/Contact/Contact.h new file mode 100755 index 0000000..3c2bcbe --- /dev/null +++ b/src/platform/API/Contact/Contact.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Contact.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_CONTACT_H_ +#define _API_CONTACT_CONTACT_H_ + +#include +#include +#include +#include +#include +#include "ContactProperties.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class Contact; +typedef DPL::SharedPtr ContactPtr; + +typedef std::vector ContactArray; +typedef DPL::SharedPtr ContactArrayPtr; + +class Contact : public ContactProperties +{ +public: + Contact(); + // CAUTION: The copy constructor of ContactProperties was not implemented implicitly. So use this function carefully. + Contact(const ContactProperties &contactProperties); + virtual ~Contact(); + + std::string getId() const; + void setId(const std::string value); + void setId(const int value); + bool getIdIsSet() const; + + bool getReadOnly() const; + void setReadOnly(const bool &value); + bool getReadOnlyIsSet() const; + + std::tm getLastUpdated() const; + void setLastUpdated(const std::tm &value); + bool getLastUpdatedIsSet() const; + + void clear(); + ContactPtr clone(); + +private: + std::string m_id; + bool m_readOnly; + std::tm m_lastUpdated; + + bool m_idIsSet; + bool m_readOnlyIsSet; + bool m_lastUpdatedIsSet; +}; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_CONTACT_H_ diff --git a/src/platform/API/Contact/ContactAccount.cpp b/src/platform/API/Contact/ContactAccount.cpp new file mode 100755 index 0000000..09aace2 --- /dev/null +++ b/src/platform/API/Contact/ContactAccount.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactAccount.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "ContactAccount.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +ContactAccount::ContactAccount() : + m_accountIdIsSet(false), + m_contactURIIsSet(false) +{ +} + +ContactAccount::~ContactAccount() +{ +} + +std::string ContactAccount::getAccountId() const +{ + return m_accountId; +} + +void ContactAccount::setAccountId(const std::string &value) +{ + m_accountIdIsSet = true; + m_accountId = value; +} + +bool ContactAccount::getAccountIdIsSet() const +{ + return m_accountIdIsSet; +} + + +std::string ContactAccount::getContactURI() const +{ + return m_contactURI; +} + +void ContactAccount::setContactURI(const std::string &value) +{ + m_contactURIIsSet = true; + m_contactURI = value; +} + +bool ContactAccount::getContactURIIsSet() const +{ + return m_contactURIIsSet; +} + +ContactAccountPtr ContactAccount::clone() const +{ + return ContactAccountPtr(new ContactAccount(*this)); +} + +} // Contact +} // Api +} // TizenApis diff --git a/src/platform/API/Contact/ContactAccount.h b/src/platform/API/Contact/ContactAccount.h new file mode 100755 index 0000000..7cbad95 --- /dev/null +++ b/src/platform/API/Contact/ContactAccount.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactAccount.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_CONTACT_ACCOUNT_H_ +#define _API_CONTACT_CONTACT_ACCOUNT_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Contact { + +class ContactAccount; +typedef DPL::SharedPtr ContactAccountPtr; + +typedef std::vector ContactAccountArray; +typedef DPL::SharedPtr ContactAccountArrayPtr; + +class ContactAccount +{ +public: + ContactAccount(); + ~ContactAccount(); + + std::string getAccountId() const; + void setAccountId(const std::string &value); + bool getAccountIdIsSet() const; + + std::string getContactURI() const; + void setContactURI(const std::string &value); + bool getContactURIIsSet() const; + + ContactAccountPtr clone() const; + +private: + std::string m_accountId; + std::string m_contactURI; + + bool m_accountIdIsSet; + bool m_contactURIIsSet; +}; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_CONTACT_ACCOUNT_H_ diff --git a/src/platform/API/Contact/ContactAddress.cpp b/src/platform/API/Contact/ContactAddress.cpp new file mode 100755 index 0000000..0d5f9e7 --- /dev/null +++ b/src/platform/API/Contact/ContactAddress.cpp @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactAddress.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include "ContactAddress.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +ContactAddress::ContactAddress() : + m_countryIsSet(false), + m_regionIsSet(false), + m_cityIsSet(false), + m_streetAddressIsSet(false), + m_additionalInformationIsSet(false), + m_postalCodeIsSet(false) +{ + m_types = ContactAddressTypeArrayPtr(new ContactAddressTypeArray()); +} + +ContactAddress::~ContactAddress() +{ + //nothing to do +} +std::string ContactAddress::getCountry() const +{ + return m_country; +} + +void ContactAddress::setCountry(const std::string &value) +{ + m_country = value; + m_countryIsSet = true; +} + +bool ContactAddress::getCountryIsSet() const +{ + return m_countryIsSet; +} + +std::string ContactAddress::getRegion() const +{ + return m_region; +} + +void ContactAddress::setRegion(const std::string &value) +{ + m_region = value; + m_regionIsSet = true; +} + +bool ContactAddress::getRegionIsSet() const +{ + return m_regionIsSet; +} + +std::string ContactAddress::getCity() const +{ + return m_city; +} + +void ContactAddress::setCity(const std::string &value) +{ + m_city = value; + m_cityIsSet = true; +} + +bool ContactAddress::getCityIsSet() const +{ + return m_cityIsSet; +} + +std::string ContactAddress::getStreetAddress() const +{ + return m_streetAddress; +} + +void ContactAddress::setStreetAddress(const std::string &value) +{ + m_streetAddress = value; + m_streetAddressIsSet = true; +} + +bool ContactAddress::getStreetAddressIsSet() const +{ + return m_streetAddressIsSet; +} + +std::string ContactAddress::getAdditionalInformation() const +{ + return m_additionalInformation; +} + +void ContactAddress::setAdditionalInformation(const std::string &value) +{ + m_additionalInformation = value; + m_additionalInformationIsSet = true; +} + +bool ContactAddress::getAdditionalInformationIsSet() const +{ + return m_additionalInformationIsSet; +} + +std::string ContactAddress::getPostalCode() const +{ + return m_postalCode; +} + +void ContactAddress::setPostalCode(const std::string &value) +{ + m_postalCode = value; + m_postalCodeIsSet = true; +} + +bool ContactAddress::getPostalCodeIsSet() const +{ + return m_postalCodeIsSet; +} + +ContactAddressTypeArrayPtr ContactAddress::getTypes() const +{ + return m_types; +} + +void ContactAddress::setTypes(const ContactAddressTypeArrayPtr &value) +{ + m_types = value; +} + +void ContactAddress::addType(const ContactAddressType &value) +{ + m_types->push_back(value); +} + +bool ContactAddress::isTypeOf(const ContactAddressType &value) const +{ + return std::find(m_types->begin(), m_types->end(), value) != m_types->end(); +} + +int ContactAddress::getTypesNum() const +{ + return m_types->size(); +} + + +bool ContactAddress::compareTo(const ContactAddressPtr &address, + bool includeId, + bool includeTypes) const +{ + //compare basic fields + if ((!includeId) && + m_country == address->getCountry() && + m_region == address->getRegion() && + m_city == address->getCity() && + m_streetAddress == address->getStreetAddress() && + m_additionalInformation == address->getAdditionalInformation() && + m_postalCode == address->getPostalCode()) { + //if not include fields then addresses are equal + if (!includeTypes) { + return true; + } + //if types have different sizes then addresses are different + if (m_types->size() != address->getTypes()->size()) { + return false; + } + //compare each type + for (size_t i = 0; i < address->getTypes()->size(); i++) { + if (!isTypeOf(address->getTypes()->at(i))) { + return false; + } + } + return true; + } + return false; +} + +ContactAddressPtr ContactAddress::clone() const +{ + //clone object by using copy constructors + return ContactAddressPtr(new ContactAddress(*this)); +} + +std::string ContactAddress::getAsSingleString() const +{ + std::string fullAddress; + //add street and street number when not empty + if (!m_streetAddress.empty()) { + fullAddress = m_streetAddress; + } + //add city and postal code when not empty + if (!m_city.empty()) { + if (!fullAddress.empty()) { + fullAddress += " "; + } + if (!m_postalCode.empty()) { + fullAddress += m_postalCode + " " + m_city; + } else { + fullAddress += m_city; + } + } + //add country when not empty + if (!m_country.empty()) { + if (!fullAddress.empty()) { + fullAddress += " " + m_country; + } else { + fullAddress = m_country; + } + } + if (!fullAddress.empty()) { + return fullAddress; + } + //when no data on detailed fields, then return free form field + return ""; +} + +} // Contact +} // Api +} // TizenApis diff --git a/src/platform/API/Contact/ContactAddress.h b/src/platform/API/Contact/ContactAddress.h new file mode 100755 index 0000000..8d683d6 --- /dev/null +++ b/src/platform/API/Contact/ContactAddress.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactAddress.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_CONTACT_ADDRESS_H_ +#define _API_CONTACT_CONTACT_ADDRESS_H_ + +#include +#include +#include +#include "ContactTypes.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class ContactAddress; +typedef DPL::SharedPtr ContactAddressPtr; + +typedef std::vector ContactAddressArray; +typedef DPL::SharedPtr ContactAddressArrayPtr; + +typedef std::vector ContactAddressTypeArray; +typedef DPL::SharedPtr ContactAddressTypeArrayPtr; + +/* This object represents an address data of a contact */ +class ContactAddress +{ +public: + ContactAddress(); + ~ContactAddress(); + + std::string getCountry() const; + void setCountry(const std::string &value); + bool getCountryIsSet() const; + + std::string getRegion() const; + void setRegion(const std::string &value); + bool getRegionIsSet() const; + + std::string getCity() const; + void setCity(const std::string &value); + bool getCityIsSet() const; + + std::string getStreetAddress() const; + void setStreetAddress(const std::string &value); + bool getStreetAddressIsSet() const; + + std::string getAdditionalInformation() const; + void setAdditionalInformation(const std::string &value); + bool getAdditionalInformationIsSet() const; + + std::string getPostalCode() const; + void setPostalCode(const std::string &value); + bool getPostalCodeIsSet() const; + + ContactAddressTypeArrayPtr getTypes() const; + void setTypes(const ContactAddressTypeArrayPtr &value); + void addType(const ContactAddressType &value); + bool isTypeOf(const ContactAddressType &value) const; + int getTypesNum() const; + + //returns m_country, ..., m_postalCode + //fields concatenated into single string + std::string getAsSingleString() const; + + bool compareTo(const ContactAddressPtr &address, + bool includeId = false, + bool includeTypes = false) const; + ContactAddressPtr clone() const; + +private: + std::string m_country; + std::string m_region; + std::string m_city; + std::string m_streetAddress; + std::string m_additionalInformation; + std::string m_postalCode; + ContactAddressTypeArrayPtr m_types; + + bool m_countryIsSet; + bool m_regionIsSet; + bool m_cityIsSet; + bool m_streetAddressIsSet; + bool m_additionalInformationIsSet; + bool m_postalCodeIsSet; +}; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_CONTACT_ADDRESS_H_ diff --git a/src/platform/API/Contact/ContactAnniversary.cpp b/src/platform/API/Contact/ContactAnniversary.cpp new file mode 100755 index 0000000..7d9f2f4 --- /dev/null +++ b/src/platform/API/Contact/ContactAnniversary.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactAnniversary.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "ContactAnniversary.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +ContactAnniversary::ContactAnniversary() : + m_dateIsSet(false), + m_labelIsSet(false) +{ +} + +ContactAnniversary::~ContactAnniversary() +{ +} + +std::tm ContactAnniversary::getDate() const +{ + return m_date; +} + +void ContactAnniversary::setDate(const std::tm &value) +{ + m_date = value; + m_dateIsSet = true; +} + +bool ContactAnniversary::getDateIsSet() const +{ + return m_dateIsSet; +} + +std::string ContactAnniversary::getLabel() const +{ + return m_label; +} + +void ContactAnniversary::setLabel(const std::string &value) +{ + m_label = value; + m_labelIsSet = true; +} + +bool ContactAnniversary::getLabelIsSet() const +{ + return m_labelIsSet; +} + +ContactAnniversaryPtr ContactAnniversary::clone() const +{ + return ContactAnniversaryPtr(new ContactAnniversary(*this)); +} + +} // Contact +} // Api +} // TizenApis diff --git a/src/platform/API/Contact/ContactAnniversary.h b/src/platform/API/Contact/ContactAnniversary.h new file mode 100755 index 0000000..72b1109 --- /dev/null +++ b/src/platform/API/Contact/ContactAnniversary.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactAnniversary.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_CONTACT_ANNIVERSARY_H_ +#define _API_CONTACT_CONTACT_ANNIVERSARY_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Contact { + +class ContactAnniversary; +typedef DPL::SharedPtr ContactAnniversaryPtr; + +typedef std::vector ContactAnniversaryArray; +typedef DPL::SharedPtr ContactAnniversaryArrayPtr; + +/* This object represents an anniversary data of a contact */ +class ContactAnniversary +{ +public: + ContactAnniversary(); + ~ContactAnniversary(); + + std::tm getDate() const; + void setDate(const std::tm &value); + bool getDateIsSet() const; + + std::string getLabel() const; + void setLabel(const std::string &value); + bool getLabelIsSet() const; + + ContactAnniversaryPtr clone() const; + +private: + std::tm m_date; + std::string m_label; + + bool m_dateIsSet; + bool m_labelIsSet; +}; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_CONTACT_ANNIVERSARY_H_ diff --git a/src/platform/API/Contact/ContactEmailAddress.cpp b/src/platform/API/Contact/ContactEmailAddress.cpp new file mode 100755 index 0000000..60945d6 --- /dev/null +++ b/src/platform/API/Contact/ContactEmailAddress.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactEmailAddress.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "ContactEmailAddress.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +ContactEmailAddress::ContactEmailAddress() : + m_emailIsSet(false) +{ + m_types = ContactEmailAddressTypeArrayPtr(new ContactEmailAddressTypeArray()); +} + +ContactEmailAddress::~ContactEmailAddress() +{ +} + +std::string ContactEmailAddress::getEmail() const +{ + return m_email; +} + +void ContactEmailAddress::setEmail(const std::string &value) +{ + m_emailIsSet = true; + m_email = value; +} + +bool ContactEmailAddress::getEmailIsSet() const +{ + return m_emailIsSet; +} + +ContactEmailAddressTypeArrayPtr ContactEmailAddress::getTypes() const +{ + return m_types; +} + +void ContactEmailAddress::setTypes(const ContactEmailAddressTypeArrayPtr &value) +{ + m_types = value; +} + +void ContactEmailAddress::addType(ContactEmailAddressType value) +{ + m_types->push_back(value); +} + +bool ContactEmailAddress::isTypeOf(ContactEmailAddressType value) const +{ + return std::find(m_types->begin(), m_types->end(), value) != m_types->end(); +} + +int ContactEmailAddress::getTypesNum() const +{ + return m_types->size(); +} + +ContactEmailAddressPtr ContactEmailAddress::clone() const +{ + return ContactEmailAddressPtr(new ContactEmailAddress(*this)); +} + +} // Contact +} // Api +} // TizenApis diff --git a/src/platform/API/Contact/ContactEmailAddress.h b/src/platform/API/Contact/ContactEmailAddress.h new file mode 100755 index 0000000..79e6f6f --- /dev/null +++ b/src/platform/API/Contact/ContactEmailAddress.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactEmailAddress.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_CONTACT_EMAIL_ADDRESS_H_ +#define _API_CONTACT_CONTACT_EMAIL_ADDRESS_H_ + +#include +#include +#include +#include +#include "ContactTypes.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class ContactEmailAddress; +typedef DPL::SharedPtr ContactEmailAddressPtr; + +typedef std::vector ContactEmailAddressArray; +typedef DPL::SharedPtr ContactEmailAddressArrayPtr; + +typedef std::vector ContactEmailAddressTypeArray; +typedef DPL::SharedPtr ContactEmailAddressTypeArrayPtr; + +class ContactEmailAddress +{ +public: + ContactEmailAddress(); + ~ContactEmailAddress(); + + std::string getEmail() const; + void setEmail(const std::string &value); + bool getEmailIsSet() const; + + ContactEmailAddressTypeArrayPtr getTypes() const; + void setTypes(const ContactEmailAddressTypeArrayPtr &value); + void addType(ContactEmailAddressType value); + bool isTypeOf(ContactEmailAddressType value) const; + int getTypesNum() const; + + ContactEmailAddressPtr clone() const; + +private: + std::string m_email; + ContactEmailAddressTypeArrayPtr m_types; + + bool m_emailIsSet; +}; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_CONTACT_EMAIL_ADDRESS_H_ diff --git a/src/platform/API/Contact/ContactFactory.cpp b/src/platform/API/Contact/ContactFactory.cpp new file mode 100755 index 0000000..2933be9 --- /dev/null +++ b/src/platform/API/Contact/ContactFactory.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactFactory.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "ContactFactory.h" +#include + +namespace TizenApis { +namespace Api { +namespace Contact { + +IContactManagerPtr ContactFactory::createContactManager() +{ + static IContactManagerPtr result(new TizenApis::Platform::Contact::ContactManager()); +// static IContactManagerPtr result(NULL); + return result; +} + +ContactFactory& ContactFactory::getInstance() +{ + static ContactFactory theInstance; + return theInstance; +} + +} // Contact +} // Api +} // TizenApis diff --git a/src/platform/API/Contact/ContactFactory.h b/src/platform/API/Contact/ContactFactory.h new file mode 100755 index 0000000..ddd2496 --- /dev/null +++ b/src/platform/API/Contact/ContactFactory.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactFactory.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_CONTACT_FACTORY_H_ +#define _API_CONTACT_CONTACT_FACTORY_H_ + +#include +#include "IContactManager.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class ContactFactory : private DPL::Noncopyable +{ +private: + ContactFactory() + { + } +public: + static ContactFactory& getInstance(); + IContactManagerPtr createContactManager(); +}; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_CONTACT_FACTORY_H_ diff --git a/src/platform/API/Contact/ContactName.cpp b/src/platform/API/Contact/ContactName.cpp new file mode 100755 index 0000000..1b8c09e --- /dev/null +++ b/src/platform/API/Contact/ContactName.cpp @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactName.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "ContactName.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +ContactName::ContactName() : + m_prefixIsSet(false), + m_firstNameIsSet(false), + m_middleNameIsSet(false), + m_lastNameIsSet(false), + m_phoneticNameIsSet(false), + m_displayNameIsSet(false) +{ + m_nicknames = StringArrayPtr(new StringArray()); +} + +ContactName::~ContactName() +{ +} + +std::string ContactName::getPrefix() const +{ + return m_prefix; +} + +void ContactName::setPrefix(const std::string &value) +{ + m_prefix = value; + m_prefixIsSet = true; +} + +bool ContactName::getPrefixIsSet() const +{ + return m_prefixIsSet; +} + +std::string ContactName::getFirstName() const +{ + return m_firstName; +} + +void ContactName::setFirstName(const std::string &value) +{ + m_firstName = value; + m_firstNameIsSet = true; +} + +bool ContactName::getFirstNameIsSet() const +{ + return m_firstNameIsSet; +} + +std::string ContactName::getMiddleName() const +{ + return m_middleName; +} + +void ContactName::setMiddleName(const std::string &value) +{ + m_middleName = value; + m_middleNameIsSet = true; +} + +bool ContactName::getMiddleNameIsSet() const +{ + return m_middleNameIsSet; +} + +std::string ContactName::getLastName() const +{ + return m_lastName; +} + +void ContactName::setLastName(const std::string &value) +{ + m_lastName = value; + m_lastNameIsSet = true; +} + +bool ContactName::getLastNameIsSet() const +{ + return m_lastNameIsSet; +} + +StringArrayPtr ContactName::getNicknames() const +{ + return m_nicknames; +} + +void ContactName::setNicknames(const StringArrayPtr &value) +{ + m_nicknames = value; +} + +void ContactName::addNickname(const std::string &value) +{ + m_nicknames->push_back(value); +} + +int ContactName::getNicknamesNum() const +{ + return m_nicknames->size(); +} + +std::string ContactName::getPhoneticName() const +{ + return m_phoneticName; +} + +void ContactName::setPhoneticName(const std::string &value) +{ + m_phoneticName = value; + m_phoneticNameIsSet = true; +} + +bool ContactName::getPhoneticIsSet() const +{ + return m_phoneticNameIsSet; +} + +std::string ContactName::getDisplayName() const +{ + return m_displayName; +} + +void ContactName::setDisplayName(const std::string &value) +{ + m_displayName = value; + m_displayNameIsSet = true; +} + +bool ContactName::getDisplayNameIsSet() const +{ + return m_displayNameIsSet; +} + +ContactNamePtr ContactName::clone() const +{ + return ContactNamePtr(new ContactName(*this)); +} + +} // Contact +} // Api +} // TizenApis diff --git a/src/platform/API/Contact/ContactName.h b/src/platform/API/Contact/ContactName.h new file mode 100755 index 0000000..b989c80 --- /dev/null +++ b/src/platform/API/Contact/ContactName.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactName.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_CONTACT_NAME_H_ +#define _API_CONTACT_CONTACT_NAME_H_ + +#include +#include +#include +#include "ContactTypes.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class ContactName; +typedef DPL::SharedPtr ContactNamePtr; + +typedef std::vector ContactNameArray; +typedef DPL::SharedPtr ContactNameArrayPtr; + +class ContactName +{ +public: + ContactName(); + ~ContactName(); + + std::string getPrefix() const; + void setPrefix(const std::string &value); + bool getPrefixIsSet() const; + + std::string getFirstName() const; + void setFirstName(const std::string &value); + bool getFirstNameIsSet() const; + + std::string getMiddleName() const; + void setMiddleName(const std::string &value); + bool getMiddleNameIsSet() const; + + std::string getLastName() const; + void setLastName(const std::string &value); + bool getLastNameIsSet() const; + + StringArrayPtr getNicknames() const; + void setNicknames(const StringArrayPtr &value); + void addNickname(const std::string& value); + int getNicknamesNum() const; + + std::string getPhoneticName() const; + void setPhoneticName(const std::string &value); + bool getPhoneticIsSet() const; + + std::string getDisplayName() const; + void setDisplayName(const std::string &value); + bool getDisplayNameIsSet() const; + + ContactNamePtr clone() const; + +private: + std::string m_prefix; + std::string m_firstName; + std::string m_middleName; + std::string m_lastName; + StringArrayPtr m_nicknames; + std::string m_phoneticName; + std::string m_displayName; + + bool m_prefixIsSet; + bool m_firstNameIsSet; + bool m_middleNameIsSet; + bool m_lastNameIsSet; + bool m_phoneticNameIsSet; + bool m_displayNameIsSet; +}; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_CONTACT_NAME_H_ diff --git a/src/platform/API/Contact/ContactOrganization.cpp b/src/platform/API/Contact/ContactOrganization.cpp new file mode 100755 index 0000000..b628afa --- /dev/null +++ b/src/platform/API/Contact/ContactOrganization.cpp @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactOrganization.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "ContactOrganization.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +ContactOrganization::ContactOrganization() : + m_nameIsSet(false), + m_departmentIsSet(false), + m_officeIsSet(false), + m_titleIsSet(false), + m_roleIsSet(false), + m_logoURIIsSet(false) +{ +} + +ContactOrganization::~ContactOrganization() +{ +} + +std::string ContactOrganization::getName() const +{ + return m_name; +} + +void ContactOrganization::setName(const std::string &value) +{ + m_name = value; + m_nameIsSet = true; +} + +bool ContactOrganization::getNameIsSet() const +{ + return m_nameIsSet; +} + +std::string ContactOrganization::getDepartment() const +{ + return m_department; +} + +void ContactOrganization::setDepartment(const std::string &value) +{ + m_department = value; + m_departmentIsSet = true; +} + +bool ContactOrganization::getDepartmentIsSet() const +{ + return m_departmentIsSet; +} + +std::string ContactOrganization::getOffice() const +{ + return m_office; +} + +void ContactOrganization::setOffice(const std::string &value) +{ + m_office = value; + m_officeIsSet = true; +} + +bool ContactOrganization::getOfficeIsSet() const +{ + return m_officeIsSet; +} + +std::string ContactOrganization::getTitle() const +{ + return m_title; +} + +void ContactOrganization::setTitle(const std::string &value) +{ + m_title = value; + m_titleIsSet = true; +} + +bool ContactOrganization::getTitleIsSet() const +{ + return m_titleIsSet; +} + +std::string ContactOrganization::getRole() const +{ + return m_role; +} + +void ContactOrganization::setRole(const std::string &value) +{ + m_role = value; + m_roleIsSet = true; +} + +bool ContactOrganization::getRoleIsSet() const +{ + return m_roleIsSet; +} + +std::string ContactOrganization::getLogoURI() const +{ + return m_logoURI; +} + +void ContactOrganization::setLogoURI(const std::string &value) +{ + m_logoURI = value; + m_logoURIIsSet = true; +} + +bool ContactOrganization::getLogoURIIsSet() const +{ + return m_logoURIIsSet; +} + +ContactOrganizationPtr ContactOrganization::clone() const +{ + return ContactOrganizationPtr(new ContactOrganization(*this)); +} + +} // Contact +} // Api +} // TizenApis diff --git a/src/platform/API/Contact/ContactOrganization.h b/src/platform/API/Contact/ContactOrganization.h new file mode 100755 index 0000000..b8ee672 --- /dev/null +++ b/src/platform/API/Contact/ContactOrganization.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactOrganization.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_CONTACT_ORGANIZATION_H_ +#define _API_CONTACT_CONTACT_ORGANIZATION_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Contact { + +class ContactOrganization; +typedef DPL::SharedPtr ContactOrganizationPtr; + +typedef std::vector ContactOrganizationArray; +typedef DPL::SharedPtr ContactOrganizationArrayPtr; + +class ContactOrganization +{ +public: + ContactOrganization(); + ~ContactOrganization(); + + std::string getName() const; + void setName(const std::string &value); + bool getNameIsSet() const; + + std::string getDepartment() const; + void setDepartment(const std::string &value); + bool getDepartmentIsSet() const; + + std::string getOffice() const; + void setOffice(const std::string &value); + bool getOfficeIsSet() const; + + std::string getTitle() const; + void setTitle(const std::string &value); + bool getTitleIsSet() const; + + std::string getRole() const; + void setRole(const std::string &value); + bool getRoleIsSet() const; + + std::string getLogoURI() const; + void setLogoURI(const std::string &value); + bool getLogoURIIsSet() const; + + ContactOrganizationPtr clone() const; + +private: + std::string m_name; + std::string m_department; + std::string m_office; + std::string m_title; + std::string m_role; + std::string m_logoURI; + + bool m_nameIsSet; + bool m_departmentIsSet; + bool m_officeIsSet; + bool m_titleIsSet; + bool m_roleIsSet; + bool m_logoURIIsSet; +}; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_CONTACT_ORGANIZATION_H_ diff --git a/src/platform/API/Contact/ContactPhoneNumber.cpp b/src/platform/API/Contact/ContactPhoneNumber.cpp new file mode 100755 index 0000000..5e73386 --- /dev/null +++ b/src/platform/API/Contact/ContactPhoneNumber.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactPhoneNumber.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "ContactPhoneNumber.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +using namespace std; + +ContactPhoneNumber::ContactPhoneNumber() : + m_numberIsSet(false) +{ + m_types = StringArrayPtr(new StringArray()); +} + +ContactPhoneNumber::~ContactPhoneNumber() +{ +} + +std::string ContactPhoneNumber::getNumber() const +{ + return m_number; +} + +void ContactPhoneNumber::setNumber(const std::string &value) +{ + m_numberIsSet = true; + m_number = value; +} + +bool ContactPhoneNumber::getNumberIsSet() const +{ + return m_numberIsSet; +} + +StringArrayPtr ContactPhoneNumber::getTypes() const +{ + return m_types; +} + +void ContactPhoneNumber::setTypes(const StringArrayPtr &value) +{ + m_types = value; +} + +void ContactPhoneNumber::addType(const string value) +{ + m_types->push_back(value); +} + +bool ContactPhoneNumber::isTypeOf(string value) const +{ + return std::find(m_types->begin(), m_types->end(), value) != m_types->end(); +} + +int ContactPhoneNumber::getTypesNum() const +{ + return m_types->size(); +} + +ContactPhoneNumberPtr ContactPhoneNumber::clone() const +{ + return ContactPhoneNumberPtr(new ContactPhoneNumber(*this)); +} + +} // Contact +} // Api +} // TizenApis diff --git a/src/platform/API/Contact/ContactPhoneNumber.h b/src/platform/API/Contact/ContactPhoneNumber.h new file mode 100755 index 0000000..cb94748 --- /dev/null +++ b/src/platform/API/Contact/ContactPhoneNumber.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactPhoneNumber.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_CONTACT_PHONE_NUMBER_H_ +#define _API_CONTACT_CONTACT_PHONE_NUMBER_H_ + +#include +#include +#include +#include +#include "ContactTypes.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class ContactPhoneNumber; +typedef DPL::SharedPtr ContactPhoneNumberPtr; + +typedef std::vector ContactPhoneNumberArray; +typedef DPL::SharedPtr ContactPhoneNumberArrayPtr; + +typedef std::vector ContactPhoneNumberTypeArray; +typedef DPL::SharedPtr ContactPhoneNumberTypeArrayPtr; + +/* This object represents a phone number data of a contact */ +class ContactPhoneNumber +{ +public: + ContactPhoneNumber(); + ~ContactPhoneNumber(); + + std::string getNumber() const; + void setNumber(const std::string &value); + bool getNumberIsSet() const; + + StringArrayPtr getTypes() const; + void setTypes(const StringArrayPtr &value); + void addType(const std::string value); + bool isTypeOf(std::string value) const; + int getTypesNum() const; + + ContactPhoneNumberPtr clone() const; + +private: + std::string m_number; + StringArrayPtr m_types; + + bool m_numberIsSet; +}; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_CONTACT_PHONE_NUMBER_H_ diff --git a/src/platform/API/Contact/ContactProperties.cpp b/src/platform/API/Contact/ContactProperties.cpp new file mode 100755 index 0000000..2e177f1 --- /dev/null +++ b/src/platform/API/Contact/ContactProperties.cpp @@ -0,0 +1,351 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactProperties.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "ContactProperties.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +ContactProperties::ContactProperties() : + //initialize fields + m_isFavorite(false), + m_nameIsSet(false), + m_accountIsSet(false), + m_photoURIIsSet(false), + m_birthdayIsSet(false), + m_organizationIsSet(false), + m_ringtoneURIIsSet(false) +{ + LogDebug("entered"); + m_name = ContactNamePtr(new ContactName()); + m_account = ContactAccountPtr(new ContactAccount()); + m_addresses = ContactAddressArrayPtr(new ContactAddressArray()); + m_phoneNumbers = ContactPhoneNumberArrayPtr(new ContactPhoneNumberArray()); + m_emails = ContactEmailAddressArrayPtr(new ContactEmailAddressArray()); + m_birthday = {0, }; + m_anniversaries = ContactAnniversaryArrayPtr(new ContactAnniversaryArray()); + m_organization = ContactOrganizationPtr(new ContactOrganization()); + m_notes = StringArrayPtr(new StringArray()); + m_urls = ContactWebSiteArrayPtr(new ContactWebSiteArray()); + m_categories = StringArrayPtr(new StringArray()); +} + +ContactProperties::~ContactProperties() +{ + //nothing to do in destructor +// LogDebug("entered"); +} + +ContactNamePtr ContactProperties::getName() const +{ + return m_name; +} + +void ContactProperties::setName(const ContactNamePtr &value) +{ + m_name = value; + m_nameIsSet = true; +} + +bool ContactProperties::getNameIsSet() const +{ + return m_nameIsSet; +} + +ContactAccountPtr ContactProperties::getAccount() const +{ + return m_account; +} + +void ContactProperties::setAccount(const ContactAccountPtr &value) +{ + m_account = value; + m_accountIsSet = true; +} + +bool ContactProperties::getAccountIsSet() const +{ + return m_accountIsSet; +} + +ContactAddressArrayPtr ContactProperties::getAddresses() const +{ + return m_addresses; +} + +void ContactProperties::setAddresses(const ContactAddressArrayPtr &value) +{ + m_addresses = value; +} + +void ContactProperties::addAddress(const ContactAddressPtr &value) +{ + m_addresses->push_back(value); +} + +int ContactProperties::getAddressesNum() const +{ + return m_addresses->size(); +} + +std::string ContactProperties::getPhotoURI() const +{ + return m_photoURI; +} + +void ContactProperties::setPhotoURI(const std::string &value) +{ + m_photoURI = value; + m_photoURIIsSet = true; +} + +bool ContactProperties::getPhotoURIIsSet() const +{ + return m_photoURIIsSet; +} + +ContactPhoneNumberArrayPtr ContactProperties::getPhoneNumbers() const +{ + return m_phoneNumbers; +} + +void ContactProperties::setPhoneNumbers(const ContactPhoneNumberArrayPtr &value) +{ + m_phoneNumbers = value; +} + +void ContactProperties::addPhoneNumber(const ContactPhoneNumberPtr &value) +{ + m_phoneNumbers->push_back(value); +} + +int ContactProperties::getPhoneNumbersNum() const +{ + return m_phoneNumbers->size(); +} + +ContactEmailAddressArrayPtr ContactProperties::getEmails() const +{ + return m_emails; +} + +void ContactProperties::addEmail(const ContactEmailAddressPtr& value) +{ + m_emails->push_back(value); +} + +void ContactProperties::setEmails(const ContactEmailAddressArrayPtr &value) +{ + m_emails = value; +} + +int ContactProperties::getEmailsNum() const +{ + return m_emails->size(); +} + +std::tm ContactProperties::getBirthday() const +{ + return m_birthday; +} + +void ContactProperties::setBirthday(const std::tm &value) +{ + m_birthday = value; + m_birthdayIsSet = true; +} + +bool ContactProperties::getBirthdayIsSet() const +{ + return m_birthdayIsSet; +} + +ContactAnniversaryArrayPtr ContactProperties::getAnniversaries() const +{ + return m_anniversaries; +} + +void ContactProperties::setAnniversaries(const ContactAnniversaryArrayPtr &value) +{ + m_anniversaries = value; +} + +void ContactProperties::addAnniversary(const ContactAnniversaryPtr &value) +{ + m_anniversaries->push_back(value); +} + +int ContactProperties::getAnniversariesNum() const +{ + return m_anniversaries->size(); +} + +ContactOrganizationPtr ContactProperties::getOrganization() const +{ + return m_organization; +} + +void ContactProperties::setOrganization(const ContactOrganizationPtr &value) +{ + m_organization = value; + m_organizationIsSet = true; +} + +bool ContactProperties::getOrganizationIsSet() const +{ + return m_organizationIsSet; +} + +StringArrayPtr ContactProperties::getNotes() const +{ + return m_notes; +} + +void ContactProperties::setNotes(const StringArrayPtr &value) +{ + m_notes = value; +} + +void ContactProperties::addNote(const std::string &value) +{ + m_notes->push_back(value); +} + +int ContactProperties::getNotesNum() const +{ + return m_notes->size(); +} + +ContactWebSiteArrayPtr ContactProperties::getUrls() const +{ + return m_urls; +} + +void ContactProperties::setUrls(const ContactWebSiteArrayPtr &value) +{ + m_urls = value; +} + +void ContactProperties::addUrl(const ContactWebSitePtr &value) +{ + m_urls->push_back(value); +} + +int ContactProperties::getUrlsNum() const +{ + return m_urls->size(); +} + +bool ContactProperties::getIsFavorite() const +{ + return m_isFavorite; +} + +void ContactProperties::setIsFavorite(const bool &value) +{ + m_isFavorite = value; +} + +std::string ContactProperties::getRingtoneURI() const +{ + return m_ringtoneURI; +} + +bool ContactProperties::getRingtoneURIIsSet() const +{ + return m_ringtoneURIIsSet; +} + +void ContactProperties::setRingtoneURI(const std::string &value) +{ + m_ringtoneURI = value; + m_ringtoneURIIsSet = true; +} + +StringArrayPtr ContactProperties::getCategories() const +{ + return m_categories; +} + +void ContactProperties::setCategories(const StringArrayPtr &value) +{ + m_categories = value; +} + +void ContactProperties::addCategory(const std::string &value) +{ + m_categories->push_back(value); +} + +int ContactProperties::getCategoriesNum() const +{ + return m_categories->size(); +} + +void ContactProperties::clear() +{ + LogDebug("entered"); + //clear all fields + m_addresses->clear(); + m_photoURI.clear(); + m_phoneNumbers->clear(); + m_emails->clear(); + m_birthday = {0,}; + m_anniversaries->clear(); + m_urls->clear(); + m_isFavorite = false; + m_ringtoneURI.clear(); + m_categories->clear(); +} + +ContactPropertiesPtr ContactProperties::clone() +{ + // TODO + //clone object + //use default copy constructor + ContactPropertiesPtr result(new ContactProperties(*this)); + ContactAddressArrayPtr addresses; + ContactPhoneNumberArrayPtr phoneNumbers; + ContactEmailAddressArrayPtr emails; + //clone internal representation of addresses + for (std::size_t i = 0; i < m_addresses->size(); ++i) { + addresses->push_back(m_addresses->at(i)->clone()); + } + result->setAddresses(addresses); + //clone internal representation of phone numbers + for (std::size_t i = 0; i < m_phoneNumbers->size(); ++i) { + phoneNumbers->push_back(m_phoneNumbers->at(i)->clone()); + } + result->setPhoneNumbers(phoneNumbers); + //clone internal representation of emails + for (std::size_t i = 0; i < m_emails->size(); ++i) { + emails->push_back(m_emails->at(i)->clone()); + } + result->setEmails(emails); + return result; +} + +} // Contact +} // Api +} // TizenApis diff --git a/src/platform/API/Contact/ContactProperties.h b/src/platform/API/Contact/ContactProperties.h new file mode 100755 index 0000000..e98cb0f --- /dev/null +++ b/src/platform/API/Contact/ContactProperties.h @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactProperties.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_CONTACT_PROPERTIES_H_ +#define _API_CONTACT_CONTACT_PROPERTIES_H_ + +#include +#include +#include +#include +#include +#include "ContactTypes.h" +#include "ContactName.h" +#include "ContactAccount.h" +#include "ContactAddress.h" +#include "ContactPhoneNumber.h" +#include "ContactEmailAddress.h" +#include "ContactAnniversary.h" +#include "ContactOrganization.h" +#include "ContactWebSite.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class ContactProperties; +typedef DPL::SharedPtr ContactPropertiesPtr; + +typedef std::vector ContactPropertiesArray; +typedef DPL::SharedPtr ContactPropertiesArrayPtr; + +class ContactProperties +{ +public: + ContactProperties(); + virtual ~ContactProperties(); + + ContactNamePtr getName() const; + void setName(const ContactNamePtr &value); + bool getNameIsSet() const; + + ContactAccountPtr getAccount() const; + void setAccount(const ContactAccountPtr &value); + bool getAccountIsSet() const; + + ContactAddressArrayPtr getAddresses() const; + void setAddresses(const ContactAddressArrayPtr &value); + void addAddress(const ContactAddressPtr &value); + int getAddressesNum() const; + + std::string getPhotoURI() const; + void setPhotoURI(const std::string &value); + bool getPhotoURIIsSet() const; + + ContactPhoneNumberArrayPtr getPhoneNumbers() const; + void setPhoneNumbers(const ContactPhoneNumberArrayPtr &value); + void addPhoneNumber(const ContactPhoneNumberPtr &value); + int getPhoneNumbersNum() const; + + ContactEmailAddressArrayPtr getEmails() const; + void setEmails(const ContactEmailAddressArrayPtr &value); + void addEmail(const ContactEmailAddressPtr& value); + int getEmailsNum() const; + + std::tm getBirthday() const; + void setBirthday(const std::tm &value); + bool getBirthdayIsSet() const; + + ContactAnniversaryArrayPtr getAnniversaries() const; + void setAnniversaries(const ContactAnniversaryArrayPtr &value); + void addAnniversary(const ContactAnniversaryPtr &value); + int getAnniversariesNum() const; + + ContactOrganizationPtr getOrganization() const; + void setOrganization(const ContactOrganizationPtr &value); + bool getOrganizationIsSet() const; + + StringArrayPtr getNotes() const; + void setNotes(const StringArrayPtr &value); + void addNote(const std::string &value); + int getNotesNum() const; + + ContactWebSiteArrayPtr getUrls() const; + void setUrls(const ContactWebSiteArrayPtr &value); + void addUrl(const ContactWebSitePtr &value); + int getUrlsNum() const; + + bool getIsFavorite() const; + void setIsFavorite(const bool &value); + + std::string getRingtoneURI() const; + void setRingtoneURI(const std::string &value); + bool getRingtoneURIIsSet() const; + + StringArrayPtr getCategories() const; + void setCategories(const StringArrayPtr &value); + void addCategory(const std::string &value); + int getCategoriesNum() const; + + void clear(); + ContactPropertiesPtr clone(); + +private: + ContactNamePtr m_name; + ContactAccountPtr m_account; + ContactAddressArrayPtr m_addresses; + std::string m_photoURI; + ContactPhoneNumberArrayPtr m_phoneNumbers; + ContactEmailAddressArrayPtr m_emails; + std::tm m_birthday; + ContactAnniversaryArrayPtr m_anniversaries; + ContactOrganizationPtr m_organization; + StringArrayPtr m_notes; + ContactWebSiteArrayPtr m_urls; + bool m_isFavorite; + std::string m_ringtoneURI; + StringArrayPtr m_categories; + + bool m_nameIsSet; + bool m_accountIsSet; + bool m_photoURIIsSet; + bool m_birthdayIsSet; + bool m_organizationIsSet; + bool m_ringtoneURIIsSet; +}; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_CONTACT_PROPERTIES_H_ diff --git a/src/platform/API/Contact/ContactTypes.h b/src/platform/API/Contact/ContactTypes.h new file mode 100755 index 0000000..d0fe85f --- /dev/null +++ b/src/platform/API/Contact/ContactTypes.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactTypes.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_CONTACT_TYPES_H_ +#define _API_CONTACT_CONTACT_TYPES_H_ + +#include +#include + +namespace TizenApis { +namespace Api { +namespace Contact { + +typedef std::vector StringArray; +typedef DPL::SharedPtr StringArrayPtr; + +typedef std::vector AttributesOfInterestArray; +typedef DPL::SharedPtr AttributesOfInterestArrayPtr; + +enum ContactEmailAddressType +{ + CONTACT_EMAIL_TYPE_WORK , + CONTACT_EMAIL_TYPE_PREF , + CONTACT_EMAIL_TYPE_HOME +}; + +enum ContactPhoneNumberType +{ + CONTACT_PHONE_NUMBER_TYPE_WORK, + CONTACT_PHONE_NUMBER_TYPE_PREF, + CONTACT_PHONE_NUMBER_TYPE_HOME, + CONTACT_PHONE_NUMBER_TYPE_VOICE, + CONTACT_PHONE_NUMBER_TYPE_FAX, + CONTACT_PHONE_NUMBER_TYPE_MSG, + CONTACT_PHONE_NUMBER_TYPE_CELL, + CONTACT_PHONE_NUMBER_TYPE_PAGER, + CONTACT_PHONE_NUMBER_TYPE_BBS, + CONTACT_PHONE_NUMBER_TYPE_MODEM, + CONTACT_PHONE_NUMBER_TYPE_CAR, + CONTACT_PHONE_NUMBER_TYPE_ISDN, + CONTACT_PHONE_NUMBER_TYPE_VIDEO, + CONTACT_PHONE_NUMBER_TYPE_PCS +}; + +enum ContactAddressType +{ + CONTACT_ADDRESS_TYPE_WORK, + CONTACT_ADDRESS_TYPE_PREF, + CONTACT_ADDRESS_TYPE_HOME +}; + +enum ContactWebSiteType +{ + WEBSITE_TYPE_HOMEPAGE, + WEBSITE_TYPE_BLOG +}; + +enum ContactAddressBookType +{ + //SIM_ADDRESS_BOOK = 0x0000, + DEVICE_ADDRESS_BOOK = 0x000F, + PHONE_ADDRESS_BOOK = 0x00FF +}; + +enum ContactVCardFormat +{ + VCARD_21_FORMAT, + VCARD_30_FORMAT +}; + +enum ContactCapabilityType +{ + HAS_VIDEO_CAPABILITY, + HAS_VOICE_CAPABILITY, + HAS_CAMERA_CAPABILITY +}; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_CONTACT_TYPES_H_ + diff --git a/src/platform/API/Contact/ContactWebSite.cpp b/src/platform/API/Contact/ContactWebSite.cpp new file mode 100755 index 0000000..46013c5 --- /dev/null +++ b/src/platform/API/Contact/ContactWebSite.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactWebSite.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "ContactWebSite.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +ContactWebSite::ContactWebSite() : + m_urlIsSet(false), + m_typeIsSet(false) +{ +} + +ContactWebSite::~ContactWebSite() +{ +} + +std::string ContactWebSite::getUrl() const +{ + return m_url; +} + +void ContactWebSite::setUrl(const std::string &value) +{ + m_url = value; + m_urlIsSet = true; +} + +bool ContactWebSite::getUrlIsSet() const +{ + return m_urlIsSet; +} + +ContactWebSiteType ContactWebSite::getType() const +{ + return m_type; +} + +void ContactWebSite::setType(const ContactWebSiteType value) +{ + m_type = value; +} + +bool ContactWebSite::getTypeIsSet() const +{ + return m_typeIsSet; +} + +ContactWebSitePtr ContactWebSite::clone() const +{ + return ContactWebSitePtr(new ContactWebSite(*this)); +} + +} // Contact +} // Api +} // TizenApis diff --git a/src/platform/API/Contact/ContactWebSite.h b/src/platform/API/Contact/ContactWebSite.h new file mode 100755 index 0000000..33c6ad6 --- /dev/null +++ b/src/platform/API/Contact/ContactWebSite.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactWebSite.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_CONTACT_WEB_SITE_H_ +#define _API_CONTACT_CONTACT_WEB_SITE_H_ + +#include +#include +#include +#include "ContactTypes.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class ContactWebSite; +typedef DPL::SharedPtr ContactWebSitePtr; + +typedef std::vector ContactWebSiteArray; +typedef DPL::SharedPtr ContactWebSiteArrayPtr; + +class ContactWebSite +{ +public: + ContactWebSite(); + ~ContactWebSite(); + + std::string getUrl() const; + void setUrl(const std::string &value); + bool getUrlIsSet() const; + + ContactWebSiteType getType() const; + void setType(const ContactWebSiteType value); + bool getTypeIsSet() const; + + ContactWebSitePtr clone() const; + +private: + std::string m_url; + ContactWebSiteType m_type; + + bool m_urlIsSet; + bool m_typeIsSet; +}; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_CONTACT_WEB_SITE_H_ diff --git a/src/platform/API/Contact/EventAddressBookAddBatch.h b/src/platform/API/Contact/EventAddressBookAddBatch.h new file mode 100755 index 0000000..b6aad1e --- /dev/null +++ b/src/platform/API/Contact/EventAddressBookAddBatch.h @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file EventAddressBookAddBatch.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_EVENT_ADDRESS_BOOK_ADD_BATCH_H_ +#define _API_CONTACT_EVENT_ADDRESS_BOOK_ADD_BATCH_H_ + +#include +#include +#include +#include "Contact.h" +#include "ContactProperties.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class EventAddressBookAddBatch : public WrtDeviceApis::Commons::IEvent +{ +private: + bool m_result; + + /* parameters */ + ContactPropertiesArrayPtr m_contactProperties; + + bool m_contactPropertiesIsSet; + + /* results */ + ContactArrayPtr m_contacts; + + bool m_contactsIsSet; + +public: + EventAddressBookAddBatch() : + m_result(false), + m_contactPropertiesIsSet(false) + { + } + + virtual ~EventAddressBookAddBatch() + { + } + + virtual void clearOnCancel() + { + } + + void setResult(bool value) + { + m_result = value; + } + + bool getResult() const + { + return m_result; + } + + ContactPropertiesArrayPtr getContactProperties() const + { + return m_contactProperties; + } + + void setContactProperties(const ContactPropertiesArrayPtr &value) + { + m_contactProperties = value; + m_contactPropertiesIsSet = true; + } + + bool getContactPropertiesIsSet() const + { + return m_contactPropertiesIsSet; + } + + ContactArrayPtr getContacts() const + { + return m_contacts; + } + + void setContacts(const ContactArrayPtr &value) + { + m_contacts = value; + m_contactsIsSet = true; + } + + bool getContactsIsSet() const + { + return m_contactsIsSet; + } +}; + +typedef DPL::SharedPtr EventAddressBookAddBatchPtr; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_EVENT_ADDRESS_BOOK_ADD_BATCH_H_ + diff --git a/src/platform/API/Contact/EventAddressBookChangeListener.h b/src/platform/API/Contact/EventAddressBookChangeListener.h new file mode 100755 index 0000000..e270729 --- /dev/null +++ b/src/platform/API/Contact/EventAddressBookChangeListener.h @@ -0,0 +1,249 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file EventAddressBookChangeListener.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_EVENT_ADDRESS_BOOK_CHANGE_LISTENER_H_ +#define _API_CONTACT_EVENT_ADDRESS_BOOK_CHANGE_LISTENER_H_ + +#include +#include +#include +#include +#include +#include "Contact.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class EventInfoAddressBookChange; +typedef DPL::SharedPtr EventInfoAddressBookChangePtr; + +class EventAddressBookChangeListener : public WrtDeviceApis::Commons::ListenerEvent +{ +private: + EventInfoAddressBookChangePtr m_eventInfo; + +public: + EventAddressBookChangeListener(EventInfoAddressBookChangePtr &eventInfo) : m_eventInfo(eventInfo) + { + } + + EventInfoAddressBookChangePtr getEventInfo() const { return m_eventInfo; } +}; +typedef DPL::SharedPtr EventAddressBookChangeListenerPtr; + +typedef WrtDeviceApis::Commons::ListenerEventEmitter EventAddressBookChangeListenerEmitter; +typedef DPL::SharedPtr EventAddressBookChangeListenerEmitterPtr; + +class EventInfoAddressBookChange +{ +private: + +public: + EventInfoAddressBookChange() + { + } + + virtual ~EventInfoAddressBookChange() + { + } + + enum CallbackType + { + OnContactsAdded, + OnContactsUpdated, + OnContactsRemoved, + OnAddressBookReset, + OnError + }; + + virtual CallbackType getCallbackType() const = 0; +}; + +class EventInfoAddressBookChangeAdded : public EventInfoAddressBookChange +{ +private: + /* results */ + ContactArrayPtr m_contacts; + + bool m_contactsIsSet; + +public: + EventInfoAddressBookChangeAdded() : m_contactsIsSet(false) + { + } + + virtual ~EventInfoAddressBookChangeAdded() + { + } + + virtual CallbackType getCallbackType() const + { + return OnContactsAdded; + } + + ContactArrayPtr getContacts() const + { + return m_contacts; + } + + void setContacts(ContactArrayPtr contacts) + { + m_contactsIsSet = true; + m_contacts = contacts; + } + + bool getContactsIsSet() const + { + return m_contactsIsSet; + } +}; +typedef DPL::SharedPtr EventInfoAddressBookChangeAddedPtr; + +class EventInfoAddressBookChangeUpdated : public EventInfoAddressBookChange +{ +private: + /* results */ + ContactArrayPtr m_contacts; + + bool m_contactsIsSet; + +public: + EventInfoAddressBookChangeUpdated() : m_contactsIsSet(false) + { + } + + virtual ~EventInfoAddressBookChangeUpdated() + { + } + + virtual CallbackType getCallbackType() const + { + return OnContactsUpdated; + } + + ContactArrayPtr getContacts() const + { + return m_contacts; + } + + void setContacts(ContactArrayPtr contacts) + { + m_contactsIsSet = true; + m_contacts = contacts; + } + + bool getContactsIsSet() const + { + return m_contactsIsSet; + } +}; +typedef DPL::SharedPtr EventInfoAddressBookChangeUpdatedPtr; + +class EventInfoAddressBookChangeRemoved : public EventInfoAddressBookChange +{ +private: + /* results */ + StringArrayPtr m_contactIds; + + bool m_contactIdsIsSet; + +public: + EventInfoAddressBookChangeRemoved() : m_contactIdsIsSet(false) + { + } + + virtual ~EventInfoAddressBookChangeRemoved() + { + } + + virtual CallbackType getCallbackType() const + { + return OnContactsRemoved; + } + + StringArrayPtr getContactIds() const + { + return m_contactIds; + } + + void setContactIds(StringArrayPtr contactIds) + { + m_contactIdsIsSet = true; + m_contactIds = contactIds; + } + + bool getContactIdsIsSet() const + { + return m_contactIdsIsSet; + } +}; +typedef DPL::SharedPtr EventInfoAddressBookChangeRemovedPtr; + +class EventInfoAddressBookChangeReset : public EventInfoAddressBookChange +{ +private: + /* results */ + +public: + EventInfoAddressBookChangeReset() + { + } + + virtual ~EventInfoAddressBookChangeReset() + { + } + + virtual CallbackType getCallbackType() const + { + return OnAddressBookReset; + } +}; +typedef DPL::SharedPtr EventInfoAddressBookChangeResetPtr; + +class EventInfoAddressBookChangeError : public EventInfoAddressBookChange +{ +private: + /* results */ + +public: + EventInfoAddressBookChangeError() + { + } + + virtual ~EventInfoAddressBookChangeError() + { + } + + virtual CallbackType getCallbackType() const + { + return OnError; + } +}; +typedef DPL::SharedPtr EventInfoAddressBookChangeErrorPtr; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_EVENT_ADDRESS_BOOK_CHANGE_LISTENER_H_ diff --git a/src/platform/API/Contact/EventAddressBookFind.h b/src/platform/API/Contact/EventAddressBookFind.h new file mode 100755 index 0000000..08e0074 --- /dev/null +++ b/src/platform/API/Contact/EventAddressBookFind.h @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file EventAddressBookFind.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_EVENT_ADDRESS_BOOK_FIND_H_ +#define _API_CONTACT_EVENT_ADDRESS_BOOK_FIND_H_ + +#include +#include +#include +#include +#include "ContactTypes.h" +#include "Contact.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +/* Event sent while searching contacts */ +class EventAddressBookFind : public WrtDeviceApis::Commons::IEvent +{ +private: + bool m_result; + + /* parameters */ + Tizen::FilterPtr m_filter; + Tizen::SortModeArrayPtr m_sortModes; +// StringArrayPtr m_attributesOfInterest; + + bool m_filterIsSet; + bool m_sortModesIsSet; +// bool m_attributesOfInterestIsSet; + + /* results */ + ContactArrayPtr m_contacts; + + bool m_contactsIsSet; + +public: + EventAddressBookFind() : + m_result(false), + m_filterIsSet(false), + m_sortModesIsSet(false), +// m_attributesOfInterestIsSet(false), + m_contactsIsSet(false) + { + } + + virtual ~EventAddressBookFind() + { + } + + virtual void clearOnCancel() + { + } + + void setResult(bool value) + { + m_result = value; + } + + bool getResult() const + { + return m_result; + } + + Tizen::FilterPtr getFilter() const + { + return m_filter; + } + + void setFilter(const Tizen::FilterPtr &value) + { + m_filter = value; + m_filterIsSet = true; + } + + bool getFilterIsSet() const + { + return m_filterIsSet; + } + + Tizen::SortModeArrayPtr getSortModes() const + { + return m_sortModes; + } + + void setSortModes(const Tizen::SortModeArrayPtr &value) + { + m_sortModes = value; + m_sortModesIsSet = true; + } + + bool getSortModesIsSet() const + { + return m_sortModesIsSet; + } + +// StringArrayPtr getAttributesOfInterest() const +// { +// return m_attributesOfInterest; +// } +// +// void setAttributesOfInterest(const StringArrayPtr &value) +// { +// m_attributesOfInterest = value; +// m_attributesOfInterestIsSet = true; +// } +// +// bool getAttributesOfInterestIsSet() const +// { +// return m_attributesOfInterestIsSet; +// } + + ContactArrayPtr getContacts() const + { + return m_contacts; + } + + void setContacts(const ContactArrayPtr &value) + { + m_contacts = value; + m_contactsIsSet = true; + } + + bool getContactsIsSet() const + { + return m_contactsIsSet; + } +}; + +typedef DPL::SharedPtr EventAddressBookFindPtr; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_EVENT_ADDRESS_BOOK_FIND_H_ diff --git a/src/platform/API/Contact/EventAddressBookRemoveBatch.h b/src/platform/API/Contact/EventAddressBookRemoveBatch.h new file mode 100755 index 0000000..b64dceb --- /dev/null +++ b/src/platform/API/Contact/EventAddressBookRemoveBatch.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file EventAddressBookRemoveBatch.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_EVENT_ADDRESS_BOOK_REMOVE_BATCH_H_ +#define _API_CONTACT_EVENT_ADDRESS_BOOK_REMOVE_BATCH_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Contact { + +class EventAddressBookRemoveBatch : public WrtDeviceApis::Commons::IEvent +{ +private: + bool m_result; + + /* parameters */ + StringArrayPtr m_contactIds; + + bool m_contactIdsIsSet; + +public: + EventAddressBookRemoveBatch() : + m_result(false), + m_contactIdsIsSet(false) + { + } + + virtual ~EventAddressBookRemoveBatch() + { + } + + virtual void clearOnCancel() + { + } + + void setResult(bool value) + { + m_result = value; + } + + bool getResult() const + { + return m_result; + } + + StringArrayPtr getContactIds() const + { + return m_contactIds; + } + + void setContactIds(const StringArrayPtr &value) + { + m_contactIdsIsSet = true; + m_contactIds = value; + } + + bool getContactIdsIsSet() const + { + return m_contactIdsIsSet; + } +}; + +typedef DPL::SharedPtr EventAddressBookRemoveBatchPtr; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_EVENT_ADDRESS_BOOK_REMOVE_BATCH_H_ + diff --git a/src/platform/API/Contact/EventAddressBookUpdateBatch.h b/src/platform/API/Contact/EventAddressBookUpdateBatch.h new file mode 100755 index 0000000..c3be9e0 --- /dev/null +++ b/src/platform/API/Contact/EventAddressBookUpdateBatch.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file EventAddressBookUpdateBatch.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_EVENT_ADDRESS_BOOK_UPDATE_BATCH_H_ +#define _API_CONTACT_EVENT_ADDRESS_BOOK_UPDATE_BATCH_H_ + +#include +#include +#include +#include "Contact.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class EventAddressBookUpdateBatch : public WrtDeviceApis::Commons::IEvent +{ +private: + bool m_result; + + /* parameters */ + ContactArrayPtr m_contacts; + + bool m_contactsIsSet; + +public: + EventAddressBookUpdateBatch() : + m_result(false), + m_contactsIsSet(false) + { + } + + virtual ~EventAddressBookUpdateBatch() + { + } + + virtual void clearOnCancel() + { + } + + void setResult(bool value) + { + m_result = value; + } + + bool getResult() const + { + return m_result; + } + + ContactArrayPtr getContacts() const + { + return m_contacts; + } + + void setContacts(const ContactArrayPtr &value) + { + m_contacts = value; + m_contactsIsSet = true; + } + + bool getContactsIsSet() const + { + return m_contactsIsSet; + } +}; + +typedef DPL::SharedPtr EventAddressBookUpdateBatchPtr; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_EVENT_ADDRESS_BOOK_UPDATE_BATCH_H_ + diff --git a/src/platform/API/Contact/EventContactManagerGetAddressBooks.h b/src/platform/API/Contact/EventContactManagerGetAddressBooks.h new file mode 100755 index 0000000..6f18240 --- /dev/null +++ b/src/platform/API/Contact/EventContactManagerGetAddressBooks.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file EventContactManagerGetAddressBooks.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_EVENT_CONTACT_MANAGER_GET_ADDRESS_BOOKS_H_ +#define _API_CONTACT_EVENT_CONTACT_MANAGER_GET_ADDRESS_BOOKS_H_ + +#include +#include +#include +#include "IAddressBook.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class EventContactManagerGetAddressBooks : public WrtDeviceApis::Commons::IEvent +{ +private: + bool m_result; + + /* parameters */ + IAddressBookArrayPtr m_addressBooks; + + bool m_addressBooksIsSet; + +public: + EventContactManagerGetAddressBooks() : + m_result(false), + m_addressBooksIsSet(false) + { + } + + virtual ~EventContactManagerGetAddressBooks() + { + } + + virtual void clearOnCancel() + { + } + + void setResult(bool value) + { + m_result = value; + } + + bool getResult() const + { + return m_result; + } + + IAddressBookArrayPtr getAddressBooks() const + { + return m_addressBooks; + } + + void setAddressBooks(const IAddressBookArrayPtr &value) + { + m_addressBooks = value; + m_addressBooksIsSet = true; + } + + bool setAddressBooksIsSet() const + { + return m_addressBooksIsSet; + } +}; + +typedef DPL::SharedPtr EventContactManagerGetAddressBooksPtr; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_EVENT_CONTACT_MANAGER_GET_ADDRESS_BOOKS_H_ + diff --git a/src/platform/API/Contact/IAddressBook.cpp b/src/platform/API/Contact/IAddressBook.cpp new file mode 100755 index 0000000..ed623d6 --- /dev/null +++ b/src/platform/API/Contact/IAddressBook.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file IAddressBook.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include "IAddressBook.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +using namespace WrtDeviceApis::Commons; + +IAddressBook::IAddressBook(AddressBookType type) : + //initialize all receivers to work on CONTACT_THREAD thread + EventRequestReceiver< EventAddressBookAddBatch >(ThreadEnum::CONTACT_THREAD), + EventRequestReceiver< EventAddressBookUpdateBatch >(ThreadEnum::CONTACT_THREAD), + EventRequestReceiver< EventAddressBookRemoveBatch >(ThreadEnum::CONTACT_THREAD), + EventRequestReceiver< EventAddressBookFind >(ThreadEnum::CONTACT_THREAD), + m_bookType(type) +{ + //Nothing to do + LogDebug("entered"); +} + +IAddressBook::~IAddressBook() +{ + //Nothing to do +// LogDebug("entered"); +} + +IAddressBook::AddressBookType IAddressBook::getType() const +{ + //return address book type: sim or device + return m_bookType; +} + +void IAddressBook::addBatch(const EventAddressBookAddBatchPtr &event) +{ + //post event to PLATFORM implementation + EventRequestReceiver< EventAddressBookAddBatch >::PostRequest(event); +} + +void IAddressBook::updateBatch(const EventAddressBookUpdateBatchPtr &event) +{ + //post event to PLATFORM implementation + EventRequestReceiver< EventAddressBookUpdateBatch >::PostRequest(event); +} + +void IAddressBook::removeBatch(const EventAddressBookRemoveBatchPtr &event) +{ + //post event to PLATFORM implementation + EventRequestReceiver< EventAddressBookRemoveBatch >::PostRequest(event); +} + +void IAddressBook::find(const EventAddressBookFindPtr &event) +{ + //post event to PLATFORM implementation + EventRequestReceiver< EventAddressBookFind >::PostRequest(event); +} + +} // Contact +} // Api +} // TizenApis diff --git a/src/platform/API/Contact/IAddressBook.h b/src/platform/API/Contact/IAddressBook.h new file mode 100755 index 0000000..7eb72d2 --- /dev/null +++ b/src/platform/API/Contact/IAddressBook.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file IAddressBook.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_IADDRESS_BOOK_H_ +#define _API_CONTACT_IADDRESS_BOOK_H_ + +#include +#include +#include +#include +#include +#include "EventAddressBookAddBatch.h" +#include "EventAddressBookUpdateBatch.h" +#include "EventAddressBookRemoveBatch.h" +#include "EventAddressBookFind.h" +#include "EventAddressBookChangeListener.h" +#include "IContactEventPrivateData.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class IAddressBook; +typedef DPL::SharedPtr IAddressBookPtr; + +typedef std::vector IAddressBookArray; +typedef DPL::SharedPtr IAddressBookArrayPtr; + +class IAddressBook : + public WrtDeviceApis::Commons::EventRequestReceiver< EventAddressBookAddBatch >, + public WrtDeviceApis::Commons::EventRequestReceiver< EventAddressBookUpdateBatch >, + public WrtDeviceApis::Commons::EventRequestReceiver< EventAddressBookRemoveBatch >, + public WrtDeviceApis::Commons::EventRequestReceiver< EventAddressBookFind >, + public IContactEventPrivateData +{ +public: + typedef enum + { + SIMBook, + PhoneBook + } AddressBookType; + + virtual ~IAddressBook(); + explicit IAddressBook(AddressBookType type); + + virtual ContactPropertiesPtr convertFromString(const std::string &vCardStr, const std::string &format) = 0; + virtual std::string convertToString(const ContactPtr &contact, const std::string &format) = 0; + virtual ContactPtr add(const ContactPropertiesPtr &contactProperty) = 0; + virtual void addBatch(const EventAddressBookAddBatchPtr &event); + virtual void update(const ContactPtr &contact) = 0; + virtual void updateBatch(const EventAddressBookUpdateBatchPtr &event); + virtual void remove(const std::string &id) = 0; + virtual void removeBatch(const EventAddressBookRemoveBatchPtr &event); + virtual void find(const EventAddressBookFindPtr &event); + + virtual long addChangeListener(const EventAddressBookChangeListenerEmitterPtr &emitter) = 0; + virtual void removeChangeListener(const long watchId) = 0; + + virtual AddressBookType getType() const; + virtual std::string getName() const = 0; + virtual void setName(const std::string &value) = 0; + +protected: + AddressBookType m_bookType; + + virtual void OnRequestReceived(const EventAddressBookAddBatchPtr &event) = 0; + virtual void OnRequestReceived(const EventAddressBookUpdateBatchPtr &event) = 0; + virtual void OnRequestReceived(const EventAddressBookRemoveBatchPtr &event) = 0; + virtual void OnRequestReceived(const EventAddressBookFindPtr &event) = 0; +}; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_IADDRESS_BOOK_H_ diff --git a/src/platform/API/Contact/IContactEventPrivateData.h b/src/platform/API/Contact/IContactEventPrivateData.h new file mode 100755 index 0000000..d426058 --- /dev/null +++ b/src/platform/API/Contact/IContactEventPrivateData.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactEventPrivateData.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_ICONTACT_EVENT_PRIVATE_DATA_H_ +#define _API_CONTACT_ICONTACT_EVENT_PRIVATE_DATA_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Contact { + +/* This is base class for objects stored as private data inside some contact events */ +class IContactEventPrivateData +{ +}; + +typedef DPL::SharedPtr IContactEventPrivateDataPtr; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_ICONTACT_EVENT_PRIVATE_DATA_H_ diff --git a/src/platform/API/Contact/IContactManager.cpp b/src/platform/API/Contact/IContactManager.cpp new file mode 100755 index 0000000..6c228ee --- /dev/null +++ b/src/platform/API/Contact/IContactManager.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file IContactManager.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include "IContactManager.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +using namespace WrtDeviceApis::Commons; + +IContactManager::IContactManager() : + EventRequestReceiver< EventContactManagerGetAddressBooks >(ThreadEnum::CONTACT_THREAD) +{ + //Nothing to do +} + +IContactManager::~IContactManager() +{ + //Nothing to do +} + +void IContactManager::getAddressBooks(const EventContactManagerGetAddressBooksPtr &event) +{ + //post event to PLATFORM implementation + EventRequestReceiver< EventContactManagerGetAddressBooks >::PostRequest(event); +} + +} // Contact +} // Api +} // TizenApis diff --git a/src/platform/API/Contact/IContactManager.h b/src/platform/API/Contact/IContactManager.h new file mode 100755 index 0000000..fe68102 --- /dev/null +++ b/src/platform/API/Contact/IContactManager.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file IContactManager.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_CONTACT_ICONTACT_MANAGER_H_ +#define _API_CONTACT_ICONTACT_MANAGER_H_ + +#include +#include +#include "IAddressBook.h" +#include "EventContactManagerGetAddressBooks.h" + +namespace TizenApis { +namespace Api { +namespace Contact { + +class IContactManager : + public WrtDeviceApis::Commons::EventRequestReceiver< EventContactManagerGetAddressBooks > +{ +public: + IContactManager(); + virtual ~IContactManager(); + virtual void getAddressBooks(const EventContactManagerGetAddressBooksPtr &event); + virtual IAddressBookPtr getDefaultAddressBook() = 0; + +protected: + virtual void OnRequestReceived(const EventContactManagerGetAddressBooksPtr &event) = 0; +}; + +typedef DPL::SharedPtr IContactManagerPtr; + +} // Contact +} // Api +} // TizenApis + +#endif // _API_CONTACT_ICONTACT_MANAGER_H_ diff --git a/src/platform/API/Contact/config.cmake b/src/platform/API/Contact/config.cmake new file mode 100755 index 0000000..73204e2 --- /dev/null +++ b/src/platform/API/Contact/config.cmake @@ -0,0 +1,17 @@ +get_current_path() +set(SRCS_PLATFORM_API_CONTACT + ${CURRENT_PATH}/IAddressBook.cpp + ${CURRENT_PATH}/IContactManager.cpp + ${CURRENT_PATH}/Contact.cpp + ${CURRENT_PATH}/ContactProperties.cpp + ${CURRENT_PATH}/ContactName.cpp + ${CURRENT_PATH}/ContactAccount.cpp + ${CURRENT_PATH}/ContactAnniversary.cpp + ${CURRENT_PATH}/ContactAddress.cpp + ${CURRENT_PATH}/ContactFactory.cpp + ${CURRENT_PATH}/ContactPhoneNumber.cpp + ${CURRENT_PATH}/ContactEmailAddress.cpp + ${CURRENT_PATH}/ContactOrganization.cpp + ${CURRENT_PATH}/ContactWebSite.cpp + PARENT_SCOPE +) diff --git a/src/platform/API/Filter/AnyType.cpp b/src/platform/API/Filter/AnyType.cpp new file mode 100755 index 0000000..5602043 --- /dev/null +++ b/src/platform/API/Filter/AnyType.cpp @@ -0,0 +1,260 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * @file AnyType.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSFilter class + */ + +#include "AnyType.h" +#include + +namespace TizenApis { +namespace Api { +namespace Tizen { + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +AnyTypeConverter::AnyTypeConverter(JSContextRef context) : + Converter(context) +{ +} + +AnyTypeConverter::~AnyTypeConverter() +{ +} + +JSValueRef AnyTypeConverter::toJSValueRef(const AnyPtr& arg) +{ + PrimitiveType type = arg->getType(); + + if(type == PrimitiveType_Boolean) + return DPL::DynamicPointerCast< Any_T >(arg)->toJSValueRef(m_context); + else if(type == PrimitiveType_Char) + return DPL::DynamicPointerCast< Any_T >(arg)->toJSValueRef(m_context); + else if(type == PrimitiveType_UChar) + return DPL::DynamicPointerCast< Any_T >(arg)->toJSValueRef(m_context); + else if(type == PrimitiveType_Int) + return DPL::DynamicPointerCast< Any_T >(arg)->toJSValueRef(m_context); + else if(type == PrimitiveType_UInt) + return DPL::DynamicPointerCast< Any_T >(arg)->toJSValueRef(m_context); + else if(type == PrimitiveType_Long) + return DPL::DynamicPointerCast< Any_T >(arg)->toJSValueRef(m_context); + else if(type == PrimitiveType_ULong) + return DPL::DynamicPointerCast< Any_T >(arg)->toJSValueRef(m_context); + else if(type == PrimitiveType_Double) + return DPL::DynamicPointerCast< Any_T >(arg)->toJSValueRef(m_context); + else if(type == PrimitiveType_String) + return DPL::DynamicPointerCast< Any_T >(arg)->toJSValueRef(m_context); + else if(type == PrimitiveType_Time) + return DPL::DynamicPointerCast< Any_T >(arg)->toJSValueRef(m_context); + else + return DPL::DynamicPointerCast< Any_T >(arg)->toJSValueRef(m_context); +} + +AnyPtr AnyTypeConverter::toAny(const JSValueRef &value, const PrimitiveType preferredNumberType) +{ + JSType jstype = JSValueGetType(m_context, value); + + if(jstype == kJSTypeBoolean) + return toAny(Converter::toBool(value)); + else if(jstype == kJSTypeNumber) + { + if(preferredNumberType == PrimitiveType_Char) + return toAny(Converter::toChar(value)); + else if(preferredNumberType == PrimitiveType_UChar) + return toAny(Converter::toUChar(value)); + else if(preferredNumberType == PrimitiveType_Int) + return toAny(Converter::toInt(value)); + else if(preferredNumberType == PrimitiveType_UInt) + return toAny(static_cast(Converter::toULong(value))); + else if(preferredNumberType == PrimitiveType_Long) + return toAny(Converter::toLong(value)); + else if(preferredNumberType == PrimitiveType_ULong) + return toAny(Converter::toULong(value)); + else if(preferredNumberType == PrimitiveType_Double) + return toAny(Converter::toDouble(value)); + else + return toAny(Converter::toDouble(value)); + } + else if(jstype == kJSTypeString) + return toAny(Converter::toString(value)); + else if(isDate(value)) + return toAny(Converter::toDateTm(value)); + else + return toAny(Converter::toString(value)); +} + +AnyPtr AnyTypeConverter::toAny(const bool &value) +{ + AnyPtr ptr(new Any_T(value)); + return ptr; +} + +AnyPtr AnyTypeConverter::toAny(const char &value) +{ + AnyPtr ptr(new Any_T(value)); + return ptr; +} + +AnyPtr AnyTypeConverter::toAny(const unsigned char &value) +{ + AnyPtr ptr(new Any_T(value)); + return ptr; +} + +AnyPtr AnyTypeConverter::toAny(const int &value) +{ + AnyPtr ptr(new Any_T(value)); + return ptr; +} + +AnyPtr AnyTypeConverter::toAny(const unsigned int &value) +{ + AnyPtr ptr(new Any_T(value)); + return ptr; +} + +AnyPtr AnyTypeConverter::toAny(const long &value) +{ + AnyPtr ptr(new Any_T(value)); + return ptr; +} + +AnyPtr AnyTypeConverter::toAny(const unsigned long &value) +{ + AnyPtr ptr(new Any_T(value)); + return ptr; +} + +AnyPtr AnyTypeConverter::toAny(const double &value) +{ + AnyPtr ptr(new Any_T(value)); + return ptr; +} + +AnyPtr AnyTypeConverter::toAny(const std::string &value) +{ + AnyPtr ptr(new Any_T(value)); + return ptr; +} + +AnyPtr AnyTypeConverter::toAny(const tm &value) +{ + AnyPtr ptr(new Any_T(value)); + return ptr; +} + +bool AnyTypeConverter::toBool(const AnyPtr& arg) +{ + if(arg->getType() != PrimitiveType_Boolean) + ThrowMsg(InvalidArgumentException, "Type mismatch."); + + return DPL::DynamicPointerCast< Any_T >(arg)->getValue(); +} + +char AnyTypeConverter::toChar(const AnyPtr& arg) +{ + if(arg->getType() != PrimitiveType_Char) + ThrowMsg(InvalidArgumentException, "Type mismatch."); + + return DPL::DynamicPointerCast< Any_T >(arg)->getValue(); +} + +unsigned char AnyTypeConverter::toUChar(const AnyPtr& arg) +{ + if(arg->getType() != PrimitiveType_UChar) + ThrowMsg(InvalidArgumentException, "Type mismatch."); + + return DPL::DynamicPointerCast< Any_T >(arg)->getValue(); +} + +int AnyTypeConverter::toInt(const AnyPtr& arg) +{ + if(arg->getType() != PrimitiveType_Int) + ThrowMsg(InvalidArgumentException, "Type mismatch."); + + return DPL::DynamicPointerCast< Any_T >(arg)->getValue(); +} + +unsigned int AnyTypeConverter::toUInt(const AnyPtr& arg) +{ + if(arg->getType() != PrimitiveType_UInt) + ThrowMsg(InvalidArgumentException, "Type mismatch."); + + return DPL::DynamicPointerCast< Any_T >(arg)->getValue(); +} + +long AnyTypeConverter::toLong(const AnyPtr& arg) +{ + if(arg->getType() != PrimitiveType_Long) + ThrowMsg(InvalidArgumentException, "Type mismatch."); + + return DPL::DynamicPointerCast< Any_T >(arg)->getValue(); +} + +unsigned long AnyTypeConverter::toULong(const AnyPtr& arg) +{ + if(arg->getType() != PrimitiveType_ULong) + ThrowMsg(InvalidArgumentException, "Type mismatch."); + + return DPL::DynamicPointerCast< Any_T >(arg)->getValue(); +} + +double AnyTypeConverter::toDouble(const AnyPtr& arg) +{ + if(arg->getType() != PrimitiveType_Double) + ThrowMsg(InvalidArgumentException, "Type mismatch."); + + return DPL::DynamicPointerCast< Any_T >(arg)->getValue(); +} + +std::string AnyTypeConverter::toString(const AnyPtr& arg) +{ + if(arg->getType() != PrimitiveType_String) + ThrowMsg(InvalidArgumentException, "Type mismatch."); + + return DPL::DynamicPointerCast< Any_T >(arg)->getValue(); +} + +tm AnyTypeConverter::toDateTm(const AnyPtr& arg) +{ + if(arg->getType() != PrimitiveType_Time) + ThrowMsg(InvalidArgumentException, "Type mismatch."); + + return DPL::DynamicPointerCast< Any_T >(arg)->getValue(); +} + +bool AnyTypeConverter::isDate(const JSValueRef& arg) +{ + // this method originated from TizenApis::Commons::Validator::isDate() + if ( JSValueIsNull( m_context, arg ) || JSValueIsUndefined( m_context, arg ) || !JSValueIsObject( m_context, arg ) ) + return false; + + Try { + toDateTm( arg ); + } Catch(Exception) { + return false; + } + return true; +} + +} // Tizen +} // Api +} // TizenApis diff --git a/src/platform/API/Filter/AnyType.h b/src/platform/API/Filter/AnyType.h new file mode 100755 index 0000000..9669934 --- /dev/null +++ b/src/platform/API/Filter/AnyType.h @@ -0,0 +1,340 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * @file AnyType.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSFilter class + */ + +#ifndef _API_ANYTYPE_H_ +#define _API_ANYTYPE_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Tizen { + +#define _PT_NOTYPE (0) +#define _PT_BOOLEAN (1 << 0) +#define _PT_CHAR (1 << 1) +#define _PT_UCHAR (1 << 2) +#define _PT_INT (1 << 3) +#define _PT_UINT (1 << 4) +#define _PT_LONG (1 << 5) +#define _PT_ULONG (1 << 6) +#define _PT_DOUBLE (1 << 7) +#define _PT_STRING (1 << 8) +#define _PT_TIME (1 << 9) +#define _PT_OTHER (1 << 10) + +enum PrimitiveType { + PrimitiveType_Notype = _PT_NOTYPE, + PrimitiveType_Boolean = _PT_BOOLEAN, + PrimitiveType_Char = _PT_CHAR, + PrimitiveType_UChar = _PT_UCHAR, + PrimitiveType_Int = _PT_INT, + PrimitiveType_UInt = _PT_UINT, + PrimitiveType_Long = _PT_LONG, + PrimitiveType_ULong = _PT_ULONG, + PrimitiveType_Double = _PT_DOUBLE, + PrimitiveType_String = _PT_STRING, + PrimitiveType_Time = _PT_TIME, + PrimitiveType_Other = _PT_OTHER, + PrimitiveType_Number = (_PT_CHAR | _PT_UCHAR | _PT_INT | _PT_UINT | + _PT_LONG | _PT_ULONG | _PT_DOUBLE), + PrimitiveType_Any = (_PT_BOOLEAN | _PT_CHAR | _PT_UCHAR | _PT_INT | + _PT_UINT | _PT_LONG | _PT_ULONG | _PT_DOUBLE | + _PT_STRING | _PT_TIME | _PT_OTHER ) +}; + +class Any +{ +public: + virtual std::string toString() const = 0; + virtual PrimitiveType getType() const = 0; +}; + +typedef DPL::SharedPtr AnyPtr; + +template +class Any_Common : public Any +{ +protected: + T m_value; + +public: + explicit Any_Common(const T& value) { m_value = value; }; + virtual ~Any_Common() {} + + virtual T getValue() const { return m_value; } + virtual void setValue(const T& value) { m_value = value; } + + virtual JSValueRef toJSValueRef(JSContextRef context) const + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + return converter.toJSValueRef(m_value); + } +}; + +template +class Any_Common : public Any +{ +protected: + T* m_value; + +public: + explicit Any_Common(const T* value) { m_value = value; } + virtual ~Any_Common() {} + + T* getValue() const { return m_value; } + void setValue(const T* value) { m_value = value; } + + virtual std::string toString() const = 0; + + virtual JSValueRef toJSValueRef(JSContextRef context) const + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + + return converter.toJSValueRef(&m_value); + } +}; + +template +class Any_T : public Any_Common +{ +public: + explicit Any_T(const T& value) : Any_Common(value) {} + virtual PrimitiveType getType() const { return PrimitiveType_Other; } + + virtual std::string toString() const + { + return ""; + } +}; + +template<> +class Any_T : public Any_Common +{ +public: + explicit Any_T(const bool& value) : Any_Common(value) {} + virtual PrimitiveType getType() const { return PrimitiveType_Boolean; } + + virtual std::string toString() const + { + if(m_value) + return "true"; + else + return "false"; + } +}; + +template<> +class Any_T : public Any_Common +{ +public: + explicit Any_T(const char& value) : Any_Common(value) {} + virtual PrimitiveType getType() const { return PrimitiveType_Char; } + + virtual std::string toString() const + { + std::stringstream oss; + oss << m_value; + return oss.str(); + } +}; + +template<> +class Any_T : public Any_Common +{ +public: + explicit Any_T(const unsigned char& value) : Any_Common(value) {} + virtual PrimitiveType getType() const { return PrimitiveType_UChar; } + + virtual std::string toString() const + { + std::stringstream oss; + oss << m_value; + return oss.str(); + } +}; + +template<> +class Any_T : public Any_Common +{ +public: + explicit Any_T(const int& value) : Any_Common(value) {} + virtual PrimitiveType getType() const { return PrimitiveType_Int; } + + virtual std::string toString() const + { + std::stringstream oss; + oss << m_value; + return oss.str(); + } +}; + +template<> +class Any_T : public Any_Common +{ +public: + explicit Any_T(const unsigned int& value) : Any_Common(value) {} + virtual PrimitiveType getType() const { return PrimitiveType_UChar; } + + virtual std::string toString() const + { + std::stringstream oss; + oss << m_value; + return oss.str(); + } +}; + +template<> +class Any_T : public Any_Common +{ +public: + explicit Any_T(const long& value) : Any_Common(value) {} + virtual PrimitiveType getType() const { return PrimitiveType_Long; } + + virtual std::string toString() const + { + std::stringstream oss; + oss << m_value; + return oss.str(); + } +}; + +template<> +class Any_T : public Any_Common +{ +public: + explicit Any_T(const unsigned long& value) : Any_Common(value) {} + virtual PrimitiveType getType() const { return PrimitiveType_ULong; } + + virtual std::string toString() const + { + std::stringstream oss; + oss << m_value; + return oss.str(); + } +}; + +template<> +class Any_T : public Any_Common +{ +public: + explicit Any_T(const double& value) : Any_Common(value) {} + virtual PrimitiveType getType() const { return PrimitiveType_Double; } + + virtual std::string toString() const + { + std::stringstream oss; + oss << m_value; + return oss.str(); + } +}; + +template<> +class Any_T : public Any_Common +{ +public: + explicit Any_T(const std::string& value) : Any_Common(value) {} + virtual PrimitiveType getType() const { return PrimitiveType_String; } + + virtual std::string toString() const + { + return m_value; + } +}; + +template<> +class Any_T : public Any_Common +{ +public: + explicit Any_T(const tm& value) : Any_Common(value) {} + virtual PrimitiveType getType() const { return PrimitiveType_Time; } + + virtual std::string toString() const + { + std::stringstream oss; + + oss << std::setfill('0') << std::setiosflags(std::ios::right) << std::setw(4) << (m_value.tm_year + 1900); + oss << std::setfill('0') << std::setiosflags(std::ios::right) << std::setw(2) << (m_value.tm_mon + 1); + oss << std::setfill('0') << std::setiosflags(std::ios::right) << std::setw(2) << m_value.tm_mday; + oss << std::setfill('0') << std::setiosflags(std::ios::right) << std::setw(2) << m_value.tm_hour; + oss << std::setfill('0') << std::setiosflags(std::ios::right) << std::setw(2) << m_value.tm_min; + oss << std::setfill('0') << std::setiosflags(std::ios::right) << std::setw(2) << m_value.tm_sec; + + return oss.str(); + } +}; + +class AnyTypeConverter : public WrtDeviceApis::CommonsJavaScript::Converter +{ +public: + explicit AnyTypeConverter(JSContextRef context); + virtual ~AnyTypeConverter(); + + JSValueRef toJSValueRef(const AnyPtr& arg); + AnyPtr toAny(const JSValueRef &value, const PrimitiveType preferredNumberType=PrimitiveType_Double); + + AnyPtr toAny(const bool &value); + AnyPtr toAny(const char &value); + AnyPtr toAny(const unsigned char &value); + AnyPtr toAny(const int &value); + AnyPtr toAny(const unsigned int &value); + AnyPtr toAny(const long &value); + AnyPtr toAny(const unsigned long &value); + AnyPtr toAny(const double &value); + AnyPtr toAny(const std::string &value); + AnyPtr toAny(const tm &value); + + bool toBool(const AnyPtr& arg); + char toChar(const AnyPtr& arg); + unsigned char toUChar(const AnyPtr& arg); + int toInt(const AnyPtr& arg); + unsigned int toUInt(const AnyPtr& arg); + long toLong(const AnyPtr& arg); + unsigned long toULong(const AnyPtr& arg); + double toDouble(const AnyPtr& arg); + std::string toString(const AnyPtr& arg); + tm toDateTm(const AnyPtr& arg); + + using WrtDeviceApis::CommonsJavaScript::Converter::toJSValueRef; + using WrtDeviceApis::CommonsJavaScript::Converter::toString; + using WrtDeviceApis::CommonsJavaScript::Converter::toDateTm; + +protected: + bool isDate(const JSValueRef& arg); +}; + +typedef WrtDeviceApis::CommonsJavaScript::ConverterFactory AnyTypeConverterFactory; +// TODO How about processing Any types with JSON??? + +typedef std::vector AnyArray; +typedef DPL::SharedPtr AnyArrayPtr; + +} // Tizen +} // Api +} // TizenApis + +#endif // _API_ANYTYPE_H_ diff --git a/src/platform/API/Filter/AttributeFilter.cpp b/src/platform/API/Filter/AttributeFilter.cpp new file mode 100755 index 0000000..532c6fd --- /dev/null +++ b/src/platform/API/Filter/AttributeFilter.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file AttributeFilter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "AttributeFilter.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +using namespace std; + +AttributeFilter::AttributeFilter(const string attributeName, + const AnyArrayPtr& matchValues, + const string& matchFlag, + const bool caseSensitive) : + m_attributeName(attributeName), + m_matchValues(matchValues), + m_matchFlag(matchFlag), + m_caseSensitive(caseSensitive) +{ +} + +AttributeFilter::~AttributeFilter() +{ +} + +string AttributeFilter::getAttributeName() const +{ + return m_attributeName; +} + +void AttributeFilter::setAttributeName(const string &value) +{ + m_attributeName = value; +} + +bool AttributeFilter::validate(FilterValidatorPtr& validator, int depth) +{ + return validator->validateAttribute(m_attributeName, m_matchValues, m_matchFlag, m_caseSensitive, depth); +} + +void AttributeFilter::travel(IFilterVisitorPtr& visitor, int depth) +{ + visitor->visitAttribute(m_attributeName, m_matchValues, m_matchFlag, m_caseSensitive, depth); +} + +AnyArrayPtr AttributeFilter::getMatchValues() const +{ + return m_matchValues; +} + +void AttributeFilter::setMatchValues(const AnyArrayPtr &value) +{ + m_matchValues = value; +} + +string AttributeFilter::getMatchFlag() const +{ + return m_matchFlag; +} + +void AttributeFilter::setMatchFlag(const string& value) +{ + m_matchFlag = value; +} + +bool AttributeFilter::getCaseSensitive() const +{ + return m_caseSensitive; +} + +void AttributeFilter::setCaseSensitive(const bool& value) +{ + m_caseSensitive = value; +} + +} // Tizen +} // Api +} // TizenApis diff --git a/src/platform/API/Filter/AttributeFilter.h b/src/platform/API/Filter/AttributeFilter.h new file mode 100755 index 0000000..a1cf8ed --- /dev/null +++ b/src/platform/API/Filter/AttributeFilter.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file AttributeFilter.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_ATTRIBUTE_FILTER_H_ +#define _API_ATTRIBUTE_FILTER_H_ + +#include +#include +#include "AnyType.h" +#include "IFilter.h" +#include "FilterTypes.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +class AttributeFilter : public IFilter +{ +private: // fields + + /** + * attribute name object + */ + std::string m_attributeName; + + /** + * match value object. + */ + AnyArrayPtr m_matchValues; + + /** + * match value object. + */ + std::string m_matchFlag; + + /** + * match value object. + */ + bool m_caseSensitive; + +protected: + +public: // methods + + /** + * constructor of abstraction filter + */ + explicit AttributeFilter(const std::string attributeName, + const AnyArrayPtr& matchValues, + const std::string& matchFlag, + const bool caseSensitive); + + virtual ~AttributeFilter(); + + /** + * method used to identify filter type + */ + virtual FilterType getFilterType() const + { + return ATTRIBUTE_FILTER; + } + + virtual bool setFilterType(const FilterType& filterType) { return false; }; + + virtual bool validate(FilterValidatorPtr& validator, int depth = 0); + + virtual void travel(IFilterVisitorPtr& traversal, int depth = 0); + + std::string getAttributeName() const; + void setAttributeName(const std::string &value); + + AnyArrayPtr getMatchValues() const; + void setMatchValues(const AnyArrayPtr &value); + + std::string getMatchFlag() const; + void setMatchFlag(const std::string& value); + + bool getCaseSensitive() const; + void setCaseSensitive(const bool &value); +}; + +typedef DPL::SharedPtr AttributeFilterPtr; + +} // Tizen +} // Api +} // TizenApis + +#endif // _API_ATTRIBUTE_FILTER_H_ diff --git a/src/platform/API/Filter/AttributeRangeFilter.cpp b/src/platform/API/Filter/AttributeRangeFilter.cpp new file mode 100755 index 0000000..df49ce2 --- /dev/null +++ b/src/platform/API/Filter/AttributeRangeFilter.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file AttributeRangeFilter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "AttributeRangeFilter.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +using namespace std; + +AttributeRangeFilter::AttributeRangeFilter(const string& attributeName, + const AnyPtr& initialValue, + const AnyPtr& endValue) : + m_attributeName(attributeName), + m_initialValue(initialValue), + m_endValue(endValue) +{ +} + +AttributeRangeFilter::~AttributeRangeFilter() +{ +} + +bool AttributeRangeFilter::validate(FilterValidatorPtr& validator, int depth) +{ + return validator->validateAttributeRange(m_attributeName, m_initialValue, m_endValue, depth); +} + +void AttributeRangeFilter::travel(IFilterVisitorPtr& visitor, int depth) +{ + visitor->visitAttributeRange(m_attributeName, m_initialValue, m_endValue, depth); +} + +string AttributeRangeFilter::getAttributeName() const +{ + return m_attributeName; +} + +AnyPtr AttributeRangeFilter::getInitialValue() const +{ + return m_initialValue; +} + +AnyPtr AttributeRangeFilter::getEndValue() const +{ + return m_endValue; +} + +void AttributeRangeFilter::setAttributeName(const string& attributeName) +{ + m_attributeName = attributeName; +} + +void AttributeRangeFilter::setInitialValue(const AnyPtr& initialValue) +{ + m_initialValue = initialValue; +} + +void AttributeRangeFilter::setEndValue(const AnyPtr& endValue) +{ + m_endValue = endValue; +} + +} // Tizen +} // Api +} // TizenApis diff --git a/src/platform/API/Filter/AttributeRangeFilter.h b/src/platform/API/Filter/AttributeRangeFilter.h new file mode 100755 index 0000000..7b65c28 --- /dev/null +++ b/src/platform/API/Filter/AttributeRangeFilter.h @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file AttributeRangeFilter.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_ATTRIBUTE_RANGE_FILTER_H_ +#define _API_ATTRIBUTE_RANGE_FILTER_H_ + +#include +#include +#include "AnyType.h" +#include "IFilter.h" +#include "FilterTypes.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +class AttributeRangeFilter : public IFilter +{ +private: // fields + /** + * attribute name + */ + std::string m_attributeName; + + /** + * initial value + */ + AnyPtr m_initialValue; + + /** + * end value + */ + AnyPtr m_endValue; + +protected: + +public: // methods + /** + * constructor of abstraction filter + */ + explicit AttributeRangeFilter(const std::string& attributeName, + const AnyPtr& initialValue, + const AnyPtr& endValue); + + virtual ~AttributeRangeFilter(); + + /** + * method used to identify filter type + */ + virtual FilterType getFilterType() const + { + return ATTRIBUTE_RANGE_FILTER; + } + virtual bool setFilterType(const FilterType& filterType) { return false; }; + + virtual bool validate(FilterValidatorPtr& validator, int depth = 0); + + virtual void travel(IFilterVisitorPtr& visitor, int depth = 0); + + /** + * method used to get attribute name + */ + std::string getAttributeName() const; + + /** + * method used to get initial value + */ + AnyPtr getInitialValue() const; + + /** + * method used to get end value + */ + AnyPtr getEndValue() const; + + /** + * method used to set attribute name + */ + void setAttributeName(const std::string& attributeName); + + /** + * method used to set initial value + */ + void setInitialValue(const AnyPtr& initialValue); + + /** + * method used to set end value + */ + void setEndValue(const AnyPtr& endValue); +}; + +typedef DPL::SharedPtr AttributeRangeFilterPtr; + +} // Tizen +} // Api +} // TizenApis + +#endif // _API_ATTRIBUTE_RANGE_FILTER_H_ diff --git a/src/platform/API/Filter/CompositeFilter.cpp b/src/platform/API/Filter/CompositeFilter.cpp new file mode 100755 index 0000000..58715ef --- /dev/null +++ b/src/platform/API/Filter/CompositeFilter.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file CompositeFilter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "CompositeFilter.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +CompositeFilter::CompositeFilter(const FilterType& type, const FilterArrayPtr& filters) : + m_filters(filters) +{ + if(type != UNION_FILTER && type != INTERSECTION_FILTER) + m_type = UNION_FILTER; + else + m_type = type; +} + +CompositeFilter::~CompositeFilter() +{ +} + +FilterType CompositeFilter::getFilterType() const +{ + return m_type; +} + +bool CompositeFilter::setFilterType(const FilterType& filterType) +{ + if(filterType != UNION_FILTER && filterType != INTERSECTION_FILTER) + return false; + + m_type = filterType; + return true; +} + +bool CompositeFilter::validate(FilterValidatorPtr& validator, int depth) +{ + FilterArray::iterator it; + + for(it=m_filters->begin(); it != m_filters->end(); it++) + { + if(!(*it)->validate(validator, depth+1)) + return false; + } + + return validator->validateComposite(depth); +} + +void CompositeFilter::travel(IFilterVisitorPtr& visitor, int depth) +{ + visitor->visitPreComposite(m_type, depth); + + FilterArray::iterator it = m_filters->begin(); + if(it != m_filters->end()) + { + while(1) + { + (*it)->travel(visitor, depth+1); + + if(++it == m_filters->end()) + break; + + visitor->visitInComposite(m_type, depth); + } + } + + visitor->visitPostComposite(m_type, depth); +} + +FilterArrayPtr CompositeFilter::getFilters() const +{ + return m_filters; +} + +void CompositeFilter::setFilters(const FilterArrayPtr& value) +{ + m_filters = value; +} + +} // Tizen +} // Api +} // TizenApis diff --git a/src/platform/API/Filter/CompositeFilter.h b/src/platform/API/Filter/CompositeFilter.h new file mode 100755 index 0000000..702a503 --- /dev/null +++ b/src/platform/API/Filter/CompositeFilter.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file CompositeFilter.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_COMPOSITE_FILTER_H_ +#define _API_COMPOSITE_FILTER_H_ + +#include +#include +#include "IFilter.h" +#include "FilterTypes.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +class CompositeFilter : public IFilter +{ +private: // fields + /** + * filter type. UNION_FILTER(OR) or INTERSECTION_FILTER(AND) + */ + FilterType m_type; + + /** + * filter array. + */ + FilterArrayPtr m_filters; + +protected: + +public: // methods + /** + * constructor of abstraction filter + * @param[in] filterType - type of filter according to FilterType + */ + explicit CompositeFilter(const FilterType& type, const FilterArrayPtr& filters); + + virtual ~CompositeFilter(); + + /** + * method used to identify filter type + */ + virtual FilterType getFilterType() const; + + virtual bool setFilterType(const FilterType& filterType); + + virtual bool validate(FilterValidatorPtr& validator, int depth = 0); + + virtual void travel(IFilterVisitorPtr& visitor, int depth = 0); + + FilterArrayPtr getFilters() const; + void setFilters(const FilterArrayPtr& value); +}; + +typedef DPL::SharedPtr CompositeFilterPtr; + +} // Tizen +} // Api +} // TizenApis + +#endif // _API_COMPOSITE_FILTER_H_ diff --git a/src/platform/API/Filter/FilterFactory.cpp b/src/platform/API/Filter/FilterFactory.cpp new file mode 100755 index 0000000..c143cc4 --- /dev/null +++ b/src/platform/API/Filter/FilterFactory.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file FilterFactory.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "FilterFactory.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +using namespace std; + +CompositeFilterPtr FilterFactory::createCompositeFilterObject(const FilterType& type, + const FilterArrayPtr& filters) +{ + CompositeFilterPtr result(new CompositeFilter(type, filters)); + return result; +} + +AttributeFilterPtr FilterFactory::createAttributeFilterObject(const string& attributeName, + const AnyArrayPtr& matchValues, + const string& matchFlag, + const bool caseSensitive) +{ + AttributeFilterPtr result(new AttributeFilter(attributeName, matchValues, matchFlag, caseSensitive)); + return result; +} + +AttributeRangeFilterPtr FilterFactory::createAttributeRangeFilterObject(const string& attributeName, + const AnyPtr& initialValue, + const AnyPtr& endValue) +{ + AttributeRangeFilterPtr result(new AttributeRangeFilter(attributeName, initialValue, endValue)); + return result; +} + +SortModePtr FilterFactory::createSortModeObject(const string& attributeName, const SortOrder& type) +{ + SortModePtr result(new SortMode(attributeName, type)); + return result; +} + +FilterFactory& FilterFactory::getInstance() +{ + static FilterFactory theInstance; + return theInstance; +} + +} // Tizen +} // Api +} // TizenApis diff --git a/src/platform/API/Filter/FilterFactory.h b/src/platform/API/Filter/FilterFactory.h new file mode 100755 index 0000000..d119096 --- /dev/null +++ b/src/platform/API/Filter/FilterFactory.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file FilterFactory.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_FILTER_FACTORY_H_ +#define _API_FILTER_FACTORY_H_ + +#include +#include "CompositeFilter.h" +#include "AttributeFilter.h" +#include "AttributeRangeFilter.h" +#include "SortMode.h" +#include "AnyType.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +class FilterFactory : private DPL::Noncopyable +{ +private: + FilterFactory() + { + } + +public: + static FilterFactory& getInstance(); + + CompositeFilterPtr createCompositeFilterObject(const FilterType& type, + const FilterArrayPtr& filters); + + AttributeFilterPtr createAttributeFilterObject(const std::string& attributeName, + const AnyArrayPtr& matchValues, + const std::string& matchFlag, + const bool caseSensitive); + + AttributeRangeFilterPtr createAttributeRangeFilterObject(const std::string& attributeName, + const AnyPtr& initialValue, + const AnyPtr& endValue); + + SortModePtr createSortModeObject(const std::string& attributeName, + const SortOrder& type = ASCENDING_SORT_ORDER); +}; + +} // Tizen +} // Api +} // TizenApis + +#endif // _API_FILTER_FACTORY_H_ diff --git a/src/platform/API/Filter/FilterTypes.h b/src/platform/API/Filter/FilterTypes.h new file mode 100755 index 0000000..9892745 --- /dev/null +++ b/src/platform/API/Filter/FilterTypes.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file FilterTypes.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_FILTER_TYPES_H_ +#define _API_FILTER_TYPES_H_ + +namespace TizenApis { +namespace Api { +namespace Tizen { + +enum FilterType +{ + UNION_FILTER, + INTERSECTION_FILTER, + ATTRIBUTE_FILTER, + ATTRIBUTE_RANGE_FILTER, + FILTERTYPE_COUNT +}; + +enum MatchFlag +{ + MATCH_NONE = 0, + MATCH_EXACTLY = 1 << 0, + MATCH_CONTAINS = 1 << 1, + MATCH_STARTSWITH = 1 << 2, + MATCH_ENDSWIDTH = 1 << 3, + MATCH_EXISTS = 1 << 4 +}; + +enum SortOrder +{ + ASCENDING_SORT_ORDER = 1, + DESCENDING_SORT_ORDER = 2 +}; + +} // TizenApis +} // Api +} // TizenApis + +#endif // _API_FILTER_TYPES_H_ + diff --git a/src/platform/API/Filter/FilterValidator.cpp b/src/platform/API/Filter/FilterValidator.cpp new file mode 100755 index 0000000..7b5216e --- /dev/null +++ b/src/platform/API/Filter/FilterValidator.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file IFilterTracer.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include "FilterValidator.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +using namespace std; + +FilterValidator::FilterValidator(PropertyStructArray properties, + MatchFlagStrArray matchFlags) +{ + int i; + for(i=0; properties[i].attributeName != 0 ; i++) + m_properties[properties[i].attributeName] = + PropertyPtr(new Property(properties[i].type)); + + for(i=0; matchFlags[i] != 0; i++) + m_matchFlags[matchFlags[i]] = true; +} + +FilterValidator::~FilterValidator() +{ +} + +bool FilterValidator::validateAttribute(std::string& attrName, AnyArrayPtr& values, + std::string& matchFlag, bool caseSensitive, int depth) +{ + if(m_properties[attrName] == NULL) + return false; + + PropertyPtr prop = m_properties[attrName]; + + AnyArray::iterator arrayIter; + for(arrayIter = values->begin(); arrayIter != values->end(); arrayIter++) + if(!(prop->type & (*arrayIter)->getType())) + return false; + + if(m_matchFlags[matchFlag] == false) + return false; + + return true; +} + +bool FilterValidator::validateAttributeRange(std::string& attrName, + AnyPtr& initialValue, AnyPtr& endValue, int depth) +{ + if(m_properties[attrName] == NULL) + return false; + + PropertyPtr prop = m_properties[attrName]; + + if(prop->type != initialValue->getType()) + return false; + + if(prop->type != endValue->getType()) + return false; + + return true; +} + +bool FilterValidator::validateComposite(int depth) +{ + return true; +} + +} // Tizen +} // Api +} // TizenApis diff --git a/src/platform/API/Filter/FilterValidator.h b/src/platform/API/Filter/FilterValidator.h new file mode 100755 index 0000000..7d3c589 --- /dev/null +++ b/src/platform/API/Filter/FilterValidator.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file FilterValidator.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_FILTER_VALIDATOR_H_ +#define _API_FILTER_VALIDATOR_H_ + +#include +#include +#include +#include +#include "AnyType.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +class IFilter; +typedef DPL::SharedPtr FilterPtr; +typedef std::vector MatchFlagArray; +typedef DPL::SharedPtr MatchFlagArrayPtr; + +struct PropertyStruct +{ + const char * attributeName; + const PrimitiveType type; +}; +typedef PropertyStruct PropertyStructArray[]; + +typedef const char *MatchFlagStrArray[]; + +// GoF Visitor Pattern +class FilterValidator +{ +private: + class Property + { + public: + Property(PrimitiveType pType) : + type(pType) {} + PrimitiveType type; + }; + typedef DPL::SharedPtr PropertyPtr; + typedef std::map PropertyMap; + typedef std::map MatchFlagList; + + PropertyMap m_properties; + MatchFlagList m_matchFlags; + +public: + FilterValidator(PropertyStructArray properties, + MatchFlagStrArray matchFlag); + + virtual ~FilterValidator(); + + // validate AttributeFilter + virtual bool validateAttribute(std::string& attrName, AnyArrayPtr& values, + std::string& matchFlag, bool caseSensitive, int depth=0); + + // validate AttributeRangeFilter + virtual bool validateAttributeRange(std::string& attrName, + AnyPtr& initialValue, AnyPtr& endValue, int depth=0); + + // validate CompositeFilter + virtual bool validateComposite(int depth=0); +}; + +typedef DPL::SharedPtr FilterValidatorPtr; + +} // Tizen +} // Api +} // TizenApis + +#endif // _API_FILTER_VALIDATOR_H_ diff --git a/src/platform/API/Filter/IFilter.cpp b/src/platform/API/Filter/IFilter.cpp new file mode 100755 index 0000000..e199167 --- /dev/null +++ b/src/platform/API/Filter/IFilter.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file IFilter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "IFilter.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +IFilter::IFilter() +{ +} + +IFilter::~IFilter() +{ +} + +} // Tizen +} // Api +} // TizenApis diff --git a/src/platform/API/Filter/IFilter.h b/src/platform/API/Filter/IFilter.h new file mode 100755 index 0000000..d59c30f --- /dev/null +++ b/src/platform/API/Filter/IFilter.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file IFilter.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Represents tizen AbstractFilter + */ + +#ifndef _API_IFILTER_H_ +#define _API_IFILTER_H_ + +#include +#include +#include "FilterTypes.h" +#include "IFilterVisitor.h" +#include "FilterValidator.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +class IFilter; +typedef DPL::SharedPtr FilterPtr; + +typedef std::vector FilterArray; +typedef DPL::SharedPtr FilterArrayPtr; + +class IFilter +{ +private: // fields + +protected: + +public: // methods + + /** + * constructor of abstraction filter + */ + explicit IFilter(); + + virtual ~IFilter(); + + /** + * method used to identify filter type + */ + virtual FilterType getFilterType() const = 0; + + virtual bool setFilterType(const FilterType& filterType) = 0; + + // validator uses GoF visitor patter. + virtual bool validate(FilterValidatorPtr& validator, int depth = 0) = 0; + + // GoF visitor patter. + virtual void travel(IFilterVisitorPtr& visitor, int depth = 0) = 0; +}; + +} // Tizen +} // Api +} // TizenApis + +#endif // _API_IFILTER_H_ diff --git a/src/platform/API/Filter/IFilterVisitor.cpp b/src/platform/API/Filter/IFilterVisitor.cpp new file mode 100755 index 0000000..76e42b3 --- /dev/null +++ b/src/platform/API/Filter/IFilterVisitor.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file IFilterVisitor.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include "IFilterVisitor.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +IFilterVisitor::IFilterVisitor() +{ +} + +IFilterVisitor::~IFilterVisitor() +{ +} + +} // Tizen +} // Api +} // TizenApis diff --git a/src/platform/API/Filter/IFilterVisitor.h b/src/platform/API/Filter/IFilterVisitor.h new file mode 100755 index 0000000..38a048f --- /dev/null +++ b/src/platform/API/Filter/IFilterVisitor.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file IFilterVisitor.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_IFILTER_VISITOR_H_ +#define _API_IFILTER_VISITOR_H_ + +#include +#include +#include +#include "AnyType.h" +#include "FilterTypes.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +class IFilter; +typedef DPL::SharedPtr FilterPtr; +typedef std::vector MatchFlagArray; +typedef DPL::SharedPtr MatchFlagArrayPtr; + +// GoF Visitor Pattern +class IFilterVisitor +{ +public: + IFilterVisitor(); + virtual ~IFilterVisitor(); + + virtual void visitPreComposite(FilterType& type, int depth) = 0; + virtual void visitInComposite(FilterType& type, int depth) = 0; + virtual void visitPostComposite(FilterType& type, int depth) = 0; + virtual void visitAttribute(std::string& attrName, + AnyArrayPtr& values, std::string& matchFlag, bool caseSensitive, int depth) = 0; + virtual void visitAttributeRange(std::string& attrName, AnyPtr& initialValue, AnyPtr& endValue, int depth) = 0; +}; + +typedef DPL::SharedPtr IFilterVisitorPtr; + +} // Tizen +} // Api +} // TizenApis + +#endif // _API_IFILTER_VISITOR_H_ diff --git a/src/platform/API/Filter/SortMode.cpp b/src/platform/API/Filter/SortMode.cpp new file mode 100755 index 0000000..6e74808 --- /dev/null +++ b/src/platform/API/Filter/SortMode.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file SortMode.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "SortMode.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { +SortMode::SortMode(const std::string& attributeName, const SortOrder& order) : + m_attributeName(attributeName), + m_order(order) +{ +} + +SortMode::~SortMode() +{ +} + +SortOrder SortMode::getOrder() const +{ + return m_order; +} + +void SortMode::setOrder(SortOrder value) +{ + m_order = value; +} + +std::string SortMode::getAttributeName() const +{ + return m_attributeName; +} + +void SortMode::setAttributeName(const std::string &value) +{ + m_attributeName = value; +} + +} // Tizen +} // Api +} // TizenApis diff --git a/src/platform/API/Filter/SortMode.h b/src/platform/API/Filter/SortMode.h new file mode 100755 index 0000000..aeade28 --- /dev/null +++ b/src/platform/API/Filter/SortMode.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file SortMode.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_SORT_MODE_H_ +#define _API_SORT_MODE_H_ + +#include +#include +#include + +#include "FilterTypes.h" + +namespace TizenApis { +namespace Api { +namespace Tizen { + +class SortMode; +typedef DPL::SharedPtr SortModePtr; + +typedef std::vector SortModeArray; +typedef DPL::SharedPtr SortModeArrayPtr; + +class SortMode +{ +public: + SortMode(const std::string& attributeName, const SortOrder& order = ASCENDING_SORT_ORDER); + virtual ~SortMode(); + + SortOrder getOrder() const; + void setOrder(SortOrder value); + + std::string getAttributeName() const; + void setAttributeName(const std::string &value); + +protected: + std::string m_attributeName; + SortOrder m_order; +}; + +typedef DPL::SharedPtr SortModePtr; + +} // Tizen +} // Api +} // TizenApis + +#endif // _API_SORT_MODE_H_ diff --git a/src/platform/API/Filter/config.cmake b/src/platform/API/Filter/config.cmake new file mode 100755 index 0000000..723e635 --- /dev/null +++ b/src/platform/API/Filter/config.cmake @@ -0,0 +1,13 @@ +get_current_path() +set(SRCS_PLATFORM_API_FILTER + ${CURRENT_PATH}/AnyType.cpp + ${CURRENT_PATH}/FilterFactory.cpp + ${CURRENT_PATH}/IFilter.cpp + ${CURRENT_PATH}/CompositeFilter.cpp + ${CURRENT_PATH}/AttributeFilter.cpp + ${CURRENT_PATH}/AttributeRangeFilter.cpp + ${CURRENT_PATH}/SortMode.cpp + ${CURRENT_PATH}/IFilterVisitor.cpp + ${CURRENT_PATH}/FilterValidator.cpp + PARENT_SCOPE +) diff --git a/src/platform/API/Geocoder/EventGeocoder.h b/src/platform/API/Geocoder/EventGeocoder.h new file mode 100644 index 0000000..3b62146 --- /dev/null +++ b/src/platform/API/Geocoder/EventGeocoder.h @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +/* + * @author + */ + +#ifndef WRTPLUGINS_API_GEOLOCATION_EVENT_GEOCODER_H_ +#define WRTPLUGINS_API_GEOLOCATION_EVENT_GEOCODER_H_ + +#include "GeocoderProperties.h" + +#include +#include + +namespace TizenApis { +namespace Tizen1_0{ +namespace Api { +namespace Geocoder { + +class EventGeocoder: public WrtDeviceApis::Commons::IEvent { +public: + static const int GEOCODER_EVENT_UNKNOWN = -1; + static const int GEOCODER_EVENT_GET_POSITION = 1; + static const int GEOCODER_EVENT_GET_ADDRESS = 2; + +private: + GeocoderProperties m_props; + int m_eventType; + + std::string m_addressString; + +public: + void setLatitude(double latitude) { + m_props.latitude = latitude; + } + void setLongitude(double longitude) { + m_props.longitude = longitude; + } + void setAltitude(double altitude) { + m_props.altitude = altitude; + } + + void setCountry(const std::string& strCountry) { + m_props.strCountry = strCountry; + } + + void setRegion(const std::string& strRegion) { + m_props.strRegion= strRegion; + } + + void setCounty(const std::string& strCounty) { + m_props.strCounty = strCounty; + } + + void setCity(const std::string& strCity) { + m_props.strCity = strCity; + } + + void setStreet(const std::string& strStreet) { + m_props.strStreet = strStreet; + } + + void setStreetNumber(const std::string& strStreetNumber) { + m_props.strStreetNumber = strStreetNumber; + } + + void setPremises(const std::string& strPremises) { + m_props.strPremises = strPremises; + } + + void setAdditionalInformation(const std::string& strAdditionalInformation) { + m_props.strAdditionalInformation= strAdditionalInformation; + } + + void setPostalCode(const std::string& strPostalCode) { + m_props.strPostalCode = strPostalCode; + } + + double getLatitude() const { + return m_props.latitude; + } + double getLongitude() const { + return m_props.longitude; + } + double getAltitude() const { + return m_props.altitude; + } + + std::string getCountry() const { + return m_props.strCountry; + } + + std::string getRegion() const { + return m_props.strRegion; + } + + std::string getCounty() const { + return m_props.strCounty; + } + + std::string getCity() const { + return m_props.strCity; + } + + std::string getStreet() const { + return m_props.strStreet; + } + + std::string getStreetNumber() const { + return m_props.strStreetNumber; + } + + std::string getPremises() const { + return m_props.strPremises; + } + + std::string getAdditionalInformation() const { + return m_props.strAdditionalInformation; + } + + std::string getPostalCode() const { + return m_props.strPostalCode; + } + + void setAddressString(std::string& addressString){ + m_addressString = addressString; + } + + std::string getAddressString() const { + if(m_addressString.empty() != true){ + return m_addressString; + }else{ + std::string strAddress; + strAddress.append(getCountry()); + strAddress.append(" "); + strAddress.append(getRegion()); + strAddress.append(" "); + strAddress.append(getCounty()); + strAddress.append(" "); + strAddress.append(getCity()); + strAddress.append(" "); + strAddress.append(getStreet()); + strAddress.append(" "); + strAddress.append(getStreetNumber()); + strAddress.append(" "); + strAddress.append(getPostalCode()); + strAddress.append(" "); + strAddress.append(getPremises()); + + return strAddress; + } + } + + void setEventType(int type){ + m_eventType = type; + } + + int getEventType(){ + return m_eventType; + } + + GeocoderProperties getGeocoderProperties() const { + return m_props; + } + + EventGeocoder() { + m_props.altitude = 0; + m_props.latitude = 0; + m_props.longitude = 0; + + m_props.strCountry = ""; + m_props.strRegion = ""; + m_props.strCounty = ""; + m_props.strCity = ""; + m_props.strStreet = ""; + m_props.strStreetNumber = ""; + m_props.strPremises = ""; + m_props.strAdditionalInformation = ""; + + m_eventType = GEOCODER_EVENT_UNKNOWN; + } +}; + +typedef DPL::SharedPtr EventGeocoderPtr; + +} // Geocoder +} // Api +} +} // TizenApis + +#endif //WRTPLUGINS_API_GEOLOCATION_EVENT_GEOCODER_H_ diff --git a/src/platform/API/Geocoder/GeocoderFactory.cpp b/src/platform/API/Geocoder/GeocoderFactory.cpp new file mode 100644 index 0000000..dbc6bf1 --- /dev/null +++ b/src/platform/API/Geocoder/GeocoderFactory.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* + * @author + */ + +#include "GeocoderFactory.h" +#include + +namespace TizenApis { +namespace Tizen1_0{ +namespace Api { +namespace Geocoder { + +IGeocoderPtr GeocoderFactory::getGeocoder() { + return IGeocoderPtr(new Platform::Geocoder::Geocoder()); +} + +GeocoderFactory& GeocoderFactory::getInstance() { + static GeocoderFactory theInstance; + return theInstance; +} + +GeocoderFactory::GeocoderFactory() { +} + +} +} +} +} diff --git a/src/platform/API/Geocoder/GeocoderFactory.h b/src/platform/API/Geocoder/GeocoderFactory.h new file mode 100644 index 0000000..bd425e6 --- /dev/null +++ b/src/platform/API/Geocoder/GeocoderFactory.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* + * @author + */ + +#ifndef WRTPLUGINS_API_GEOCODERFACTORY_H_ +#define WRTPLUGINS_API_GEOCODERFACTORY_H_ + +#include +#include "IGeocoder.h" + +namespace TizenApis { +namespace Tizen1_0{ +namespace Api { +namespace Geocoder { + +class GeocoderFactory: DPL::Noncopyable { +public: + IGeocoderPtr getGeocoder(); + + static GeocoderFactory& getInstance(); + +protected: + GeocoderFactory(); +}; + +} +} +} +} + +#endif //WRTPLUGINS_API_GEOCODERFACTORY_H_ diff --git a/src/platform/API/Geocoder/GeocoderProperties.h b/src/platform/API/Geocoder/GeocoderProperties.h new file mode 100644 index 0000000..7400204 --- /dev/null +++ b/src/platform/API/Geocoder/GeocoderProperties.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* + * @author + */ + +#ifndef WRTPLUGINS_API_GEOCODER_PROPERTIES_H_ +#define WRTPLUGINS_API_GEOCODER_PROPERTIES_H_ + +#include +#include + +using namespace std; + +namespace TizenApis { +namespace Tizen1_0{ +namespace Api { +namespace Geocoder { + +struct GeocoderProperties { + double latitude; + double longitude; + double altitude; + double accuracy; + double altitudeAccuracy; + double heading; + double speed; + + std::string strCountry; + std::string strRegion; + std::string strCounty; + std::string strCity; + std::string strStreet; + std::string strStreetNumber; + std::string strPremises; + std::string strAdditionalInformation; + std::string strPostalCode; + +// std::string strCountryCode; +// std::string strState; +// std::string strDistrict; +// std::string strBuildingNumber; + GeocoderProperties() : latitude(0), longitude(0), altitude(0), accuracy(0), altitudeAccuracy(0), + heading(0), speed(0){ + } +}; + +typedef DPL::SharedPtr GeocoderPropertiesPtr; + +} // Geocoder +} // Api +} +} // WrtPlugins + +#endif //WRTPLUGINS_API_GEOCODER_PROPERTIES_H_ diff --git a/src/platform/API/Geocoder/IGeocoder.cpp b/src/platform/API/Geocoder/IGeocoder.cpp new file mode 100644 index 0000000..0c7bf08 --- /dev/null +++ b/src/platform/API/Geocoder/IGeocoder.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* + * @author + */ + +#include "IGeocoder.h" + +namespace TizenApis { +namespace Tizen1_0{ +namespace Api { +namespace Geocoder{ + +//using namespace Platform; + +//TODO check thread type +IGeocoder::IGeocoder() : + WrtDeviceApis::Commons::EventRequestReceiver(WrtDeviceApis::Commons::ThreadEnum::GEOLOCATION_THREAD) +{ +} + +IGeocoder::~IGeocoder() +{ +} + +} +} +} +} diff --git a/src/platform/API/Geocoder/IGeocoder.h b/src/platform/API/Geocoder/IGeocoder.h new file mode 100644 index 0000000..b34165c --- /dev/null +++ b/src/platform/API/Geocoder/IGeocoder.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* + * @author + */ + +#ifndef WRTPLUGINS_API_IGEOCODER_H_ +#define WRTPLUGINS_API_IGEOCODER_H_ + +#include "EventGeocoder.h" + +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Api { +namespace Geocoder { + +class EventGeocoder; +typedef DPL::SharedPtr EventGeocoderPtr; + +class IGeocoder: public WrtDeviceApis::Commons::EventRequestReceiver { +public: + + virtual ~IGeocoder(); + +// /** +// * Gets address from position +// * @param event @see WrtPlugins::Api::Geocoder::EventGeocoder. +// * @exception Commons::PlatformException when platform error occurs +// */ + virtual void getAddressFromPosition(const EventGeocoderPtr& event) = 0; + + // /** + // * Gets address from position + // * @param event @see WrtPlugins::Api::Geocoder::EventGeocoder. + // * @exception Commons::PlatformException when platform error occurs + // */ + virtual void getPositionFromAddress(const EventGeocoderPtr& event) = 0; + +protected: + IGeocoder(); + + virtual void OnRequestReceived(const EventGeocoderPtr& event) = 0; +}; + +typedef DPL::SharedPtr IGeocoderPtr; + +} +} +} +} + +#endif /* WRTPLUGINS_API_IGEOCODER_H_ */ diff --git a/src/platform/API/Geocoder/config.cmake b/src/platform/API/Geocoder/config.cmake new file mode 100644 index 0000000..8936e30 --- /dev/null +++ b/src/platform/API/Geocoder/config.cmake @@ -0,0 +1,6 @@ +get_current_path() +set(SRCS_PLATFORM_API_GEOCODER + ${CURRENT_PATH}/GeocoderFactory.cpp + ${CURRENT_PATH}/IGeocoder.cpp + PARENT_SCOPE +) diff --git a/src/platform/API/Messaging/AttachmentFactory.cpp b/src/platform/API/Messaging/AttachmentFactory.cpp new file mode 100755 index 0000000..cac6d9a --- /dev/null +++ b/src/platform/API/Messaging/AttachmentFactory.cpp @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * @file AttachmentFactory.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include "AttachmentFactory.h" +#include "Attachments.h" +#include + +using namespace std; +using namespace WrtDeviceApis::Commons; +using namespace TizenApis::Platform::Messaging; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +IAttachmentPtr AttachmentFactory::createAttachment(const std::string& fullPath, + bool isVirtualPath) +{ + LogDebug("enter"); + IAttachmentPtr attachment(new Attachment(fullPath, isVirtualPath)); + if (!attachment->getIsCreatedProperly()) { + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, + "Attachment couldn't be created"); + } + return attachment; +} +} +} +} diff --git a/src/platform/API/Messaging/AttachmentFactory.h b/src/platform/API/Messaging/AttachmentFactory.h new file mode 100755 index 0000000..ad047ae --- /dev/null +++ b/src/platform/API/Messaging/AttachmentFactory.h @@ -0,0 +1,51 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * @file AttachmentFactory.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef ATTACHMENTFACTORY_H +#define ATTACHMENTFACTORY_H + +#include +#include "IAttachment.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class AttachmentFactory +{ + public: + + /** + * Generate attachment object + * @param[in] fullPath path to file + * @param[in] isVirtualPath false when path is real file system path, true when it's path on file system exposed to user + */ + static IAttachmentPtr createAttachment(const std::string& fullPath, + bool isVirtualPath); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/Attachments.cpp b/src/platform/API/Messaging/Attachments.cpp new file mode 100755 index 0000000..4b4e350 --- /dev/null +++ b/src/platform/API/Messaging/Attachments.cpp @@ -0,0 +1,252 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IAttachment.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include +#include +#include "Attachments.h" +#include "AttachmentFactory.h" + +extern "C" { +#include +#include +} + +using namespace WrtDeviceApis::Commons; +using namespace std; + +//-------------------------------------------------------------------------- +namespace TizenApis { +namespace Api { +namespace Messaging { + +Attachments::Attachments() : + m_validAttachments(false) +{ + LogDebug("enter"); +} + +Attachments::~Attachments() +{ + LogDebug("enter"); +} + +IAttachmentPtr Attachments::appendAttachment(const std::string& fullPath, + bool isVirtualPath) +{ + LogDebug("enter, fullPath=" << fullPath); + IAttachmentPtr tmpAttach = AttachmentFactory::createAttachment( + fullPath, + isVirtualPath); + m_validAttachments = false; + m_attachments.push_back(tmpAttach); + return tmpAttach; +} + +void Attachments::appendAttachment(const IAttachmentPtr& attachment) +{ + LogDebug("enter"); + m_validAttachments = false; + m_attachments.push_back(attachment); +} + +IAttachmentPtr Attachments::appendAttachment(const IMessagePtr& message, const std::string& fullPath, + bool isVirtualPath) +{ + LogDebug("enter"); + IAttachmentPtr iAttachment = appendAttachment(fullPath, isVirtualPath); + + if (message && iAttachment) + { + iAttachment->setMessage(message); + } +} + +void Attachments::appendAttachment(const IMessagePtr& message, const IAttachmentPtr& attachment) +{ + LogDebug("enter"); + + m_validAttachments = false; + + if (attachment && message) + attachment->setMessage(message); + + m_attachments.push_back(attachment); +} + +void Attachments::appendAttachments(const vector& attachments) +{ + LogDebug("enter"); + back_insert_iterator< vector >biit(m_attachments); + copy(attachments.begin(), attachments.end(), biit); +} + +size_t Attachments::getAttachmentsCount() const +{ + LogDebug("enter"); + return m_attachments.size(); +} + +IAttachmentPtr Attachments::getAttachment(const size_t index) const +{ + LogDebug("enter"); + if (index >= m_attachments.size()) { + ThrowMsg(OutOfRangeException, "Trying to get attachment out of range"); + } + return m_attachments[index]; +} + +void Attachments::removeAttachment(const size_t index) +{ + LogDebug("enter"); + if (index >= m_attachments.size()) { + ThrowMsg(OutOfRangeException, "Trying to get attachment out of range"); + } + m_validAttachments = false; + m_attachments.erase(m_attachments.begin() + index); +} + +void Attachments::removeAttachment(const IAttachmentPtr& attachment) +{ + m_attachments.erase( + remove(m_attachments.begin(), m_attachments.end(), attachment), + m_attachments.end()); +} + +vector Attachments::getAttachments() const +{ + LogDebug("enter"); + return m_attachments; +} + +vector Attachments::getAttachmentsFullPaths() const +{ + vector retVal; + + for (size_t i = 0; i < m_attachments.size(); i++) { + retVal.push_back(m_attachments[i]->getFullPath()); + } + return retVal; +} + +vector Attachments::getAttachmentsShortNames() const +{ + vector retVal; + + for (size_t i = 0; i < m_attachments.size(); i++) { + retVal.push_back(m_attachments[i]->getShortName()); + } + return retVal; +} + +void Attachments::setAttachments(const vector& attachments, + bool isVirtualPath) +{ + vector::const_iterator it = attachments.begin(); + + m_attachments.clear(); + while (it != attachments.end()) { + appendAttachment(*it, isVirtualPath); + ++it; + } +} + +void Attachments::setAttachments(const vector& attachments) +{ + m_attachments = attachments; + m_validAttachments = false; +} + +bool Attachments::isAttachmentsValid() const +{ + return m_validAttachments; +} + +void Attachments::setAttachmentsValidity(bool state) +{ + m_validAttachments = state; +} + +const vector& Attachments::getAttachmentsRef() const +{ + return m_attachments; +} + +void Attachments::saveAttachment(const string& destFileName, + const IAttachmentPtr& attachment) +{ + // possible move it as a virtual function - to be clarified + LogError("N/A"); + //TODO +} + +void Attachments::setAttachmentWithExpand(const size_t index, + const std::string& fullPath, + bool isVirtualPath) +{ + // expand if needed + if (index >= m_attachments.size()) { + m_attachments.resize(index + 1); // resize with empty ptr + } + IAttachmentPtr tmpAttach = AttachmentFactory::createAttachment( + fullPath, + isVirtualPath); + m_attachments[index] = tmpAttach; + m_validAttachments = false; +} + +void Attachments::reverse() +{ + std::reverse(m_attachments.begin(), m_attachments.end()); +} + +void Attachments::insertAttachment(const size_t index, + const std::string& fullPath, + bool isVirtualPath) +{ + IAttachmentPtr tmpAttach = AttachmentFactory::createAttachment( + fullPath, + isVirtualPath); + m_attachments.insert(m_attachments.begin() + index, tmpAttach); + m_validAttachments = false; +} + +void Attachments::insertAttachmentWithExpand(const size_t index, + const std::string& fullPath, + bool isVirtualPath) +{ + // expand if needed + if (index >= m_attachments.size()) { + m_attachments.resize(index); // resize with empty ptr + } + IAttachmentPtr tmpAttach = AttachmentFactory::createAttachment( + fullPath, + isVirtualPath); + m_attachments.insert(m_attachments.begin() + index, tmpAttach); + m_validAttachments = false; +} +} +} +} diff --git a/src/platform/API/Messaging/Attachments.h b/src/platform/API/Messaging/Attachments.h new file mode 100755 index 0000000..75ad3a5 --- /dev/null +++ b/src/platform/API/Messaging/Attachments.h @@ -0,0 +1,226 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * @file Attachments.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef ATTACHMENTS_H +#define ATTACHMENTS_H + +#include +#include +#include +#include "IMessagingTypes.h" +#include "IAttachment.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class Attachments +{ + std::vector m_attachments; + + public: // fields + + private: + + bool m_validAttachments; + + public: // methods + + Attachments(); + + virtual ~Attachments(); + + /** + * method for append attachment into list + * @param[in] fullPath - path for attachment + * @return AttachmentPtr - if file exist create attachment object + * it is possible to modify name, etc. + * @throw InvalidArgumentException - if file not exist + */ + IAttachmentPtr appendAttachment(const std::string& fullPath, + bool isVirtualPath); + + /** + * method for append attachment into list + * @param[in] attachment - attachment to be added + */ + void appendAttachment(const IAttachmentPtr& attachment); + + /** + * method for append attachment into list + * @param[in] message - message interface + * @param[in] fullPath - path for attachment + * @return AttachmentPtr - if file exist create attachment object + * it is possible to modify name, etc. + * @throw InvalidArgumentException - if file not exist + */ + IAttachmentPtr appendAttachment(const IMessagePtr& message, const std::string& fullPath, + bool isVirtualPath); + + /** + * method for append attachment into list + * @param[in] message - message interface + * @param[in] attachment - attachment to be added + */ + void appendAttachment(const IMessagePtr& message, const IAttachmentPtr& attachment); + + /** + * method for append attachments list + * @param[in] attachments - attachment list + */ + void appendAttachments(const std::vector& attachments); + + /** + * get attachment count + * @return attachment count + */ + size_t getAttachmentsCount() const; + + /** + * get attachment object at index + * @param[in] index - index of attachment to get + * @return attachment object + * @throw OutOfRangeException if index is out of range + */ + IAttachmentPtr getAttachment(const size_t index) const; + + /** + * remove attachment at the index + * @param[in] index - index of attachment to get + * @return void + * @throw OutOfRangeException if index is out of range + */ + void removeAttachment(const size_t index); + + /** + * remove attachment at the index + * @param[in] attachment - AttachmentPtr object + * @return void + * @throw OutOfRangeException if index is out of range + */ + void removeAttachment(const IAttachmentPtr& attachment); + + /** + * get all attachments vector + * @return attachment vector + */ + std::vector getAttachments() const; + + /** + * get all attachments full path vector + * @return attachment path vector + */ + std::vector getAttachmentsFullPaths() const; + + /** + * get all attachments names vector + * @return attachment names vector + */ + std::vector getAttachmentsShortNames() const; + + /** + * get all attachments vector reference + * @return attachment vector + */ + const std::vector& getAttachmentsRef() const; + + /** + * set attachments + * @param[in] attachments - vector of and attachments full path + * @throw InvalidArgumentException - if file not exist + */ + void setAttachments(const std::vector& attachments, + bool isVirtualPath); + + /** + * set attachmentsPtr + * @param[in] attachments - vector of AttachmentPtr + */ + void setAttachments(const std::vector& attachments); + + /** + * check if attachments are modified and need update in platform + * @return bool + */ + bool isAttachmentsValid() const; + + /** + * setting validity after update + * @param[in] state - state for validity to set + */ + void setAttachmentsValidity(bool state); + + /** + * saving attachment file to selected destination file + * @param[in] destFileName - destination file to save attachment + * @param[in] attachment - attachment to be saved + */ + void saveAttachment(const std::string& destFileName, + const IAttachmentPtr& attachment); + + /** + * sets attachment at given position and expands array if needed + * @param[in] index - position + * @param[in] fullPath - path for attachment + * @throw InvalidArgumentException - if file not exist + */ + void setAttachmentWithExpand(const size_t index, + const std::string& fullPath, + bool isVirtualPath); + + /** + * The reverse() method reverses the order of the elements in an array + * (makes the last element first, and the first element last). + */ + void reverse(); + + /** + * Creates new attachment and inserts it at given position + * @param[in] index position + * @param[in] fullPath - path for attachment + * @param[in] isVirtualPath - true if path is virtual + * @throw InvalidArgumentException - if file not exist + */ + void insertAttachment(const size_t index, + const std::string& fullPath, + bool isVirtualPath); + + /** + * Creates new attachment and inserts it at given position and expands array if needed + * @param[in] index position + * @param[in] fullPath - path for attachment + * @param[in] isVirtualPath - true if path is virtual + * @throw InvalidArgumentException - if file not exist + */ + void insertAttachmentWithExpand(const size_t index, + const std::string& fullPath, + bool isVirtualPath); +}; + +typedef DPL::SharedPtr AttachmentsPtr; +} +} +} +#endif diff --git a/src/platform/API/Messaging/BccRecipient.cpp b/src/platform/API/Messaging/BccRecipient.cpp new file mode 100755 index 0000000..9f3cc21 --- /dev/null +++ b/src/platform/API/Messaging/BccRecipient.cpp @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file BccRecipient.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "BccRecipient.h" + +using namespace std; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +BccRecipient::BccRecipient() : + m_bccRecipients(new Recipients()) +{ +} + +BccRecipient::~BccRecipient() +{ +} + +void BccRecipient::setBccValidity(bool state) +{ + m_bccRecipients->setValid(state); +} + +bool BccRecipient::getBccValidity() const +{ + return m_bccRecipients->isValid(); +} + +Recipients BccRecipient::getBccRecipients() const +{ + return *m_bccRecipients; +} + +void BccRecipient::setBccRecipients(const Recipients& value) +{ + *m_bccRecipients = value; +} + +void BccRecipient::appendBccRecipients(const std::string & value) +{ + m_bccRecipients->appendRecipient(value); +} + +void BccRecipient::appendBccRecipients(const Recipients& value) +{ + *m_bccRecipients += value; +} + +void BccRecipient::removeBccRecipients(const Recipients& value) +{ + *m_bccRecipients -= value; +} + +RecipientsPtr BccRecipient::getBccRecipientsPtr() const +{ + return m_bccRecipients; +} +} +} +} diff --git a/src/platform/API/Messaging/BccRecipient.h b/src/platform/API/Messaging/BccRecipient.h new file mode 100755 index 0000000..00c64d0 --- /dev/null +++ b/src/platform/API/Messaging/BccRecipient.h @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file BccRecipient.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef BCCRECIPIENT_H +#define BCCRECIPIENT_H + +#include +#include "Recipient.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class BccRecipient +{ + private: // fields + + RecipientsPtr m_bccRecipients; + + public: + + BccRecipient(); + + virtual ~BccRecipient(); + + void setBccValidity(bool state); + + bool getBccValidity() const; + + Recipients getBccRecipients() const; + + RecipientsPtr getBccRecipientsPtr() const; + + void appendBccRecipients(const std::string & value); + + void appendBccRecipients(const Recipients& value); + + void removeBccRecipients(const Recipients& value); + + void setBccRecipients(const Recipients& value); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/Body.cpp b/src/platform/API/Messaging/Body.cpp new file mode 100755 index 0000000..dc263c7 --- /dev/null +++ b/src/platform/API/Messaging/Body.cpp @@ -0,0 +1,69 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Body.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "Body.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +Body::Body() : + m_body(""), + m_validBody(false) +{ +} + +Body::~Body() +{ +} + +void Body::setBody(const std::string& value) +{ + m_body = value; + m_validBody = false; +} + +std::string Body::getBody() const +{ + return m_body; +} + +const std::string& Body::getBodyRef() const +{ + return m_body; +} + +bool Body::isBodyValid() const +{ + return m_validBody; +} + +void Body::setBodyValidity(bool state) +{ + m_validBody = state; +} +} +} +} diff --git a/src/platform/API/Messaging/Body.h b/src/platform/API/Messaging/Body.h new file mode 100755 index 0000000..eea64ae --- /dev/null +++ b/src/platform/API/Messaging/Body.h @@ -0,0 +1,86 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Body.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef BODY_H +#define BODY_H + +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class Body +{ + private: // fields + + /** + * body value + */ + std::string m_body; //plainBody on SMS, MMS, ... + + /** + * information if abstract message body has been changed and need update + * in low level + */ + bool m_validBody; + + public: // methods + + Body(); + + virtual ~Body(); + + /** + * setter of body value + */ + void setBody(const std::string& value); + + /** + * getter of body value + */ + std::string getBody() const; + + /** + * getter of body value + */ + const std::string& getBodyRef() const; + + /** + * check body validity + * */ + bool isBodyValid() const; + + /** + * set body validity + * */ + void setBodyValidity(bool state); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/CallbackNumber.cpp b/src/platform/API/Messaging/CallbackNumber.cpp new file mode 100755 index 0000000..5e15cbf --- /dev/null +++ b/src/platform/API/Messaging/CallbackNumber.cpp @@ -0,0 +1,72 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file CallbackNumber.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include "CallbackNumber.h" +#include "CallbackNumber.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +CallbackNumber::CallbackNumber() : + m_callbackNumber(""), + m_validCallbackNumber(false) +{ +} + +CallbackNumber::~CallbackNumber() +{ +} + +void CallbackNumber::setCallbackNumber(const std::string& value) +{ + LogDebug("set callbackNumber=" << value); + m_callbackNumber = value; + m_validCallbackNumber = false; +} + +std::string CallbackNumber::getCallbackNumber() const +{ + return m_callbackNumber; +} + +const std::string& CallbackNumber::getCallbackNumberRef() const +{ + return m_callbackNumber; +} + +bool CallbackNumber::isCallbackNumberValid() const +{ + return m_validCallbackNumber; +} + +void CallbackNumber::setCallbackNumberValidity(bool state) +{ + m_validCallbackNumber = state; +} +} +} +} diff --git a/src/platform/API/Messaging/CallbackNumber.h b/src/platform/API/Messaging/CallbackNumber.h new file mode 100755 index 0000000..75e1563 --- /dev/null +++ b/src/platform/API/Messaging/CallbackNumber.h @@ -0,0 +1,86 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file CallbackNumber.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef CALLBACKNUMBER_H +#define CALLBACKNUMBER_H + +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class CallbackNumber +{ + private: // fields + + /** + * CallbackNumber value + */ + std::string m_callbackNumber; + + /** + * information if abstract message body has been changed and need update + * in low level + */ + bool m_validCallbackNumber; + + public: // methods + + CallbackNumber(); + + virtual ~CallbackNumber(); + + /** + * setter of CallbackNumber value + */ + void setCallbackNumber(const std::string& value); + + /** + * getter of CallbackNumber value + */ + std::string getCallbackNumber() const; + + /** + * getter of CallbackNumber value + */ + const std::string& getCallbackNumberRef() const; + + /** + * check CallbackNumber validity + * */ + bool isCallbackNumberValid() const; + + /** + * set CallbackNumber validity + * */ + void setCallbackNumberValidity(bool state); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/CcRecipient.cpp b/src/platform/API/Messaging/CcRecipient.cpp new file mode 100755 index 0000000..8aa6f3f --- /dev/null +++ b/src/platform/API/Messaging/CcRecipient.cpp @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file CcRecipient.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "CcRecipient.h" + +using namespace std; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +CcRecipient::CcRecipient() : + m_ccRecipients(new Recipients()) +{ +} + +CcRecipient::~CcRecipient() +{ +} + +void CcRecipient::setCcValidity(bool state) +{ + m_ccRecipients->setValid(state); +} + +bool CcRecipient::getCcValidity(void) const +{ + return m_ccRecipients->isValid(); +} + +Recipients CcRecipient::getCcRecipients() const +{ + return *m_ccRecipients; +} + +RecipientsPtr CcRecipient::getCcRecipientsPtr() const +{ + return m_ccRecipients; +} + +void CcRecipient::appendCcRecipients(const std::string & value) +{ + m_ccRecipients->appendRecipient(value); +} + +void CcRecipient::appendCcRecipients(const Recipients& value) +{ + *m_ccRecipients += value; +} + +void CcRecipient::removeCcRecipients(const Recipients& value) +{ + *m_ccRecipients -= value; +} + +void CcRecipient::setCcRecipients(const Recipients& value) +{ + *m_ccRecipients = value; +} +} +} +} diff --git a/src/platform/API/Messaging/CcRecipient.h b/src/platform/API/Messaging/CcRecipient.h new file mode 100755 index 0000000..7c3b0ab --- /dev/null +++ b/src/platform/API/Messaging/CcRecipient.h @@ -0,0 +1,69 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file CcRecipient.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef CCRECIPIENT_H +#define CCRECIPIENT_H + +#include +#include "Recipient.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class CcRecipient +{ + private: // fields + + RecipientsPtr m_ccRecipients; + + public: + + CcRecipient(); + + virtual ~CcRecipient(); + + void setCcValidity(bool state); + + bool getCcValidity(void) const; + + Recipients getCcRecipients() const; + + RecipientsPtr getCcRecipientsPtr() const; + + void appendCcRecipients(const std::string & value); + + void appendCcRecipients(const Recipients& value); + + void removeCcRecipients(const Recipients& value); + + void setCcRecipients(const Recipients& value); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/ConversationFilterValidator.cpp b/src/platform/API/Messaging/ConversationFilterValidator.cpp new file mode 100755 index 0000000..569b384 --- /dev/null +++ b/src/platform/API/Messaging/ConversationFilterValidator.cpp @@ -0,0 +1,93 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * ConversationValidator.cpp + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#include "ConversationFilterValidator.h" +#include "ConversationFilterValidatorFactory.h" + +#include + +#include + +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + ConversationFilterValidator::ConversationFilterValidator(PropertyStructArray properties, + MatchFlagStrArray matchFlag,Api::Tizen::PrimitiveType idType):FilterValidator(properties, matchFlag){ + m_isTypeSetted = false; + } + + ConversationFilterValidator::~ConversationFilterValidator() { + m_isTypeSetted = false; + } + + + bool ConversationFilterValidator::validateAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth){ + bool retVal = false; + + if(attrName.compare(ConversationFilterValidatorFactory::ATTRIBUTE_TIMESTAMP)!=0){ + LogError(">>> [ERROR] Not Supported attribute :[" << attrName << "]"); + return false; + } + + retVal = FilterValidator::validateAttributeRange(attrName, initialValue, endValue, depth); + return retVal; + } + + bool ConversationFilterValidator::validateAttribute(std::string& attrName, Api::Tizen::AnyArrayPtr& values, + std::string& matchFlag, bool caseSensitive, int depth){ + bool retBool = false; + + AnyArray::iterator iter; + for(iter=values->begin(); iter!=values->end(); iter++){ + AnyPtr value = *iter; + if(validateAttributeEach(attrName, value, matchFlag, depth) == false){ + MsgLogWanning(">>>[Warning] attrName:[" << attrName << "] is invalid value:[" << value->toString() << "]"); + return false; + } + } + + retBool = FilterValidator::validateAttribute(attrName, values, matchFlag, caseSensitive, depth); + LogDebug(">>> retBool:" << retBool); + return retBool; + } + + bool ConversationFilterValidator::validateAttributeEach(std::string& attrName,Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth){ + LogDebug("<<< attrName:[" << attrName << "], value:[" << value->toString() << "]"); + + if(attrName.compare(ConversationFilterValidatorFactory::ATTRIBUTE_TYPE)==0){ + if(m_isTypeSetted == true){ + MsgLogError(">>> [ERROR] duplicated type :[" << attrName << "], value:[" << value->toString()<< "]"); + return false; + }else{ + m_isTypeSetted = true; + } + } + + return true; + } + + } + } +} diff --git a/src/platform/API/Messaging/ConversationFilterValidator.h b/src/platform/API/Messaging/ConversationFilterValidator.h new file mode 100755 index 0000000..7b962e5 --- /dev/null +++ b/src/platform/API/Messaging/ConversationFilterValidator.h @@ -0,0 +1,60 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * ConversationValidator.h + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#ifndef CONVERSATIONFILTERVALIDATOR_H_ +#define CONVERSATIONFILTERVALIDATOR_H_ + +#include + +namespace TizenApis { + + namespace Platform { + namespace Messaging { + + class ConversationFilterValidator : public Api::Tizen::FilterValidator { + private: + bool m_isTypeSetted; + + public: + ConversationFilterValidator(Api::Tizen::PropertyStructArray properties, + Api::Tizen::MatchFlagStrArray matchFlag, Api::Tizen::PrimitiveType idType); + virtual ~ConversationFilterValidator(); + + // validate AttributeRangeFilter + virtual bool validateAttributeRange(std::string& attrName, + Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth=0); + + virtual bool validateAttribute(std::string& attrName, Api::Tizen::AnyArrayPtr& values, + std::string& matchFlag, bool caseSensitive, int depth=0); + + protected: + bool validateAttributeEach(std::string& attrName,Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth); + + }; + + typedef DPL::SharedPtr ConversationFilterValidatorPtr; + + } + } +} + +#endif /* CONVERSATIONFILTERVALIDATOR_H_ */ diff --git a/src/platform/API/Messaging/ConversationFilterValidatorFactory.cpp b/src/platform/API/Messaging/ConversationFilterValidatorFactory.cpp new file mode 100755 index 0000000..a6a2b23 --- /dev/null +++ b/src/platform/API/Messaging/ConversationFilterValidatorFactory.cpp @@ -0,0 +1,72 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * ConversationFilterValidatorFactory + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#include "ConversationFilterValidatorFactory.h" + +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + const std::string ConversationFilterValidatorFactory::ATTRIBUTE_ID = "id"; + const std::string ConversationFilterValidatorFactory::ATTRIBUTE_TYPE = "type"; + const std::string ConversationFilterValidatorFactory::ATTRIBUTE_TIMESTAMP = "timestamp"; + const std::string ConversationFilterValidatorFactory::ATTRIBUTE_MESSAGE_COUNT = "messageCount"; + const std::string ConversationFilterValidatorFactory::ATTRIBUTE_UNREAD_MESSAGES = "unreadMessages"; + const std::string ConversationFilterValidatorFactory::ATTRIBUTE_PREVIEW = "preview"; + const std::string ConversationFilterValidatorFactory::ATTRIBUTE_FROM = "from"; + const std::string ConversationFilterValidatorFactory::ATTRIBUTE_TO = "to"; + + static PropertyStructArray properties = + { + {ConversationFilterValidatorFactory::ATTRIBUTE_ID.c_str(), Api::Tizen::PrimitiveType_String}, + {ConversationFilterValidatorFactory::ATTRIBUTE_TYPE.c_str(), Api::Tizen::PrimitiveType_String}, + {ConversationFilterValidatorFactory::ATTRIBUTE_TIMESTAMP.c_str(), Api::Tizen::PrimitiveType_Time}, + {ConversationFilterValidatorFactory::ATTRIBUTE_MESSAGE_COUNT.c_str(), Api::Tizen::PrimitiveType_Number}, + {ConversationFilterValidatorFactory::ATTRIBUTE_UNREAD_MESSAGES.c_str(), Api::Tizen::PrimitiveType_Number}, + {ConversationFilterValidatorFactory::ATTRIBUTE_PREVIEW.c_str(), Api::Tizen::PrimitiveType_String}, + {ConversationFilterValidatorFactory::ATTRIBUTE_FROM.c_str(), Api::Tizen::PrimitiveType_String}, + {ConversationFilterValidatorFactory::ATTRIBUTE_TO.c_str(), Api::Tizen::PrimitiveType_String}, + {0, Api::Tizen::PrimitiveType_Notype} + }; + + static MatchFlagStrArray matchFlag{ + "EXACTLY", + "CONTAINS", + "STARTSWITH", + "ENDSWITH", +// "MATCH_CASESENSITIVE", + 0 + }; + + ConversationFilterValidatorPtr ConversationFilterValidatorFactory::getConversationFilterValidator() + { + ConversationFilterValidatorPtr theInstance = + ConversationFilterValidatorPtr(new ConversationFilterValidator(properties, matchFlag, Api::Tizen::PrimitiveType_Int)); + + return theInstance; + } + + } + } +} diff --git a/src/platform/API/Messaging/ConversationFilterValidatorFactory.h b/src/platform/API/Messaging/ConversationFilterValidatorFactory.h new file mode 100755 index 0000000..0b1ad2c --- /dev/null +++ b/src/platform/API/Messaging/ConversationFilterValidatorFactory.h @@ -0,0 +1,57 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * ConversationFilterValidatorFactory.h + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#ifndef CONVERSATIONFILTERVALIDATORFACTORY_H_ +#define CONVERSATIONFILTERVALIDATORFACTORY_H_ + +#include +#include "ConversationFilterValidator.h" + +namespace TizenApis { + + namespace Platform { + namespace Messaging { + + class ConversationFilterValidatorFactory { + public: + ConversationFilterValidatorFactory(){}; + + public: + static const std::string ATTRIBUTE_ID; + static const std::string ATTRIBUTE_TYPE; + static const std::string ATTRIBUTE_TIMESTAMP; + static const std::string ATTRIBUTE_MESSAGE_COUNT; + static const std::string ATTRIBUTE_UNREAD_MESSAGES; + static const std::string ATTRIBUTE_PREVIEW; + static const std::string ATTRIBUTE_FROM; + static const std::string ATTRIBUTE_TO; + + public: + static ConversationFilterValidatorPtr getConversationFilterValidator(); + }; + + } + } + +} + +#endif /* CONVERSATIONFILTERVALIDATORFACTORY_H_ */ diff --git a/src/platform/API/Messaging/EmailAccountInfo.cpp b/src/platform/API/Messaging/EmailAccountInfo.cpp new file mode 100755 index 0000000..410bb99 --- /dev/null +++ b/src/platform/API/Messaging/EmailAccountInfo.cpp @@ -0,0 +1,106 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ +#include +#include +#include "EmailAccountInfo.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +EmailAccountInfo::EmailAccountInfo(int id, + const std::string& name, + const std::string& address) : + m_name(name), + m_address(address) +{ + std::stringstream stream; + stream << id; + if (stream.fail()) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Couldn't convert e-mail account id"); + } + m_id = stream.str(); +} + +EmailAccountInfo::EmailAccountInfo(const std::string& id, + const std::string& name, + const std::string& address) : + m_id(id), + m_name(name), + m_address(address) +{ +} + +int EmailAccountInfo::getIntId() const +{ + int result = 0; + std::stringstream stream(m_id); + stream >> result; + if (stream.fail()) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Couldn't convert e-mail account id"); + } + return result; +} + +std::string EmailAccountInfo::getId() const +{ + return m_id; +} + +std::string EmailAccountInfo::getName() const +{ + return m_name; +} + +std::string EmailAccountInfo::getAddress() const +{ + return m_address; +} + +#if 0 +void EmailAccountInfo::setAccountData(int id, const char* name, const char* address) +{ + std::stringstream stream; + stream << id; + if (stream.fail()) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Couldn't convert e-mail account id"); + } + + //m_id = stream.str(); + //m_name = name; //name + //m_address = address; //address + + m_id = "1"; + m_name="Gmail"; + m_address = "milkelf.choi@gmail.com"; +} +#endif +const bool EmailAccountInfo::operator==(const EmailAccountInfo& account) const +{ + return (m_id == account.m_id && + m_name == account.m_name && + m_address == account.m_address); +} +} +} +} diff --git a/src/platform/API/Messaging/EmailAccountInfo.h b/src/platform/API/Messaging/EmailAccountInfo.h new file mode 100755 index 0000000..f464c34 --- /dev/null +++ b/src/platform/API/Messaging/EmailAccountInfo.h @@ -0,0 +1,64 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTPLUGINS_MESSAGING_EMAILACCOUNTINFO_H_ +#define WRTPLUGINS_MESSAGING_EMAILACCOUNTINFO_H_ + +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EmailAccountInfo +{ + public: + EmailAccountInfo(int id, + const std::string& name, + const std::string& address); + + EmailAccountInfo(const std::string& id = "", + const std::string& name = "", + const std::string& address = ""); + + int getIntId() const; + + std::string getId() const; + + std::string getName() const; + + std::string getAddress() const; + + //void setAccountData(int id, const char* name, const char* address); + + const bool operator==(const EmailAccountInfo& account) const; + + private: + std::string m_id; + std::string m_name; + std::string m_address; +}; + +//typedef DPL::SharedPtr EmailAccountInfoPtr; + +} +} +} +#endif // WRTPLUGINS_MESSAGING_EMAILACCOUNTINFO_H_ diff --git a/src/platform/API/Messaging/EmitterConversationReceived.cpp b/src/platform/API/Messaging/EmitterConversationReceived.cpp new file mode 100755 index 0000000..c146a4e --- /dev/null +++ b/src/platform/API/Messaging/EmitterConversationReceived.cpp @@ -0,0 +1,29 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "EmitterConversationReceived.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +} +} // Api +} // WrtPlugins diff --git a/src/platform/API/Messaging/EmitterConversationReceived.h b/src/platform/API/Messaging/EmitterConversationReceived.h new file mode 100755 index 0000000..3896d1a --- /dev/null +++ b/src/platform/API/Messaging/EmitterConversationReceived.h @@ -0,0 +1,41 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTPLUGINS_MESSAGING_EMITTERCONVERSATIONRECEIVED_H_ +#define WRTPLUGINS_MESSAGING_EMITTERCONVERSATIONRECEIVED_H_ + +#include +#include +#include "EventMessageReceived.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EmitterConversationReceived : public WrtDeviceApis::Commons::ListenerEventEmitter +{ + +}; + +typedef DPL::SharedPtr EmitterConversationReceivedPtr; +} // Api +} // WrtPlugins +} +#endif // WRTPLUGINS_MESSAGING_EMITTERCONVERSATIONRECEIVED_H_ diff --git a/src/platform/API/Messaging/EmitterFolderReceived.cpp b/src/platform/API/Messaging/EmitterFolderReceived.cpp new file mode 100755 index 0000000..6a62d7d --- /dev/null +++ b/src/platform/API/Messaging/EmitterFolderReceived.cpp @@ -0,0 +1,29 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "EmitterFolderReceived.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +} +} // Api +} // WrtPlugins diff --git a/src/platform/API/Messaging/EmitterFolderReceived.h b/src/platform/API/Messaging/EmitterFolderReceived.h new file mode 100755 index 0000000..b1b9ee9 --- /dev/null +++ b/src/platform/API/Messaging/EmitterFolderReceived.h @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTPLUGINS_MESSAGING_EMITTERFOLDERRECEIVED_H_ +#define WRTPLUGINS_MESSAGING_EMITTERFOLDERRECEIVED_H_ + +#include +#include +#include "EventMessageReceived.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EmitterFolderReceived : public WrtDeviceApis::Commons::ListenerEventEmitter< + EventMessageReceived> +{ + +}; + +typedef DPL::SharedPtr EmitterFolderReceivedPtr; +} // Api +} // WrtPlugins +} +#endif // WRTPLUGINS_MESSAGING_EMITTERMESSAGERECEIVED_H_ diff --git a/src/platform/API/Messaging/EmitterMessageReceived.cpp b/src/platform/API/Messaging/EmitterMessageReceived.cpp new file mode 100755 index 0000000..26b48ce --- /dev/null +++ b/src/platform/API/Messaging/EmitterMessageReceived.cpp @@ -0,0 +1,28 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "EmitterMessageReceived.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { +} +} // Api +} // WrtPlugins diff --git a/src/platform/API/Messaging/EmitterMessageReceived.h b/src/platform/API/Messaging/EmitterMessageReceived.h new file mode 100755 index 0000000..c166988 --- /dev/null +++ b/src/platform/API/Messaging/EmitterMessageReceived.h @@ -0,0 +1,41 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTPLUGINS_MESSAGING_EMITTERMESSAGERECEIVED_H_ +#define WRTPLUGINS_MESSAGING_EMITTERMESSAGERECEIVED_H_ + +#include +#include +#include "EventMessageReceived.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EmitterMessageReceived : public WrtDeviceApis::Commons::ListenerEventEmitter +{ + +}; + +typedef DPL::SharedPtr EmitterMessageReceivedPtr; +} // Api +} // WrtPlugins +} +#endif // WRTPLUGINS_MESSAGING_EMITTERMESSAGERECEIVED_H_ diff --git a/src/platform/API/Messaging/EventDeleteConversations.h b/src/platform/API/Messaging/EventDeleteConversations.h new file mode 100755 index 0000000..0e0ee44 --- /dev/null +++ b/src/platform/API/Messaging/EventDeleteConversations.h @@ -0,0 +1,78 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * + * + * @file EventDeleteConversations.h + * @author Kangsoo Lee (wpeter.lee@samsung.com) + * @version 0.1 + * @brief + */ + + +#ifndef EVENT_DELETE_CONVERSATIONS_H +#define EVENT_DELETE_CONVERSATIONS_H + +#include +#include +#include +#include "IMessage.h" +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventDeleteConversations; + +typedef DPL::SharedPtr EventDeleteConversationsPtr; + +class EventDeleteConversations : + public WrtDeviceApis::Commons::IEvent +{ +private: + std::vector m_conversations; + bool m_FilterUse; + Api::Tizen::SortModePtr m_sortMode; + Api::Tizen::FilterPtr m_filter; + unsigned long m_limit; + unsigned long m_offset; + + public: + void setSortMode(Api::Tizen::SortModePtr sortMode) { m_sortMode = sortMode;} + void setFilter(Api::Tizen::FilterPtr filter) { m_filter = filter;} + void setLimit(unsigned long limit) { m_limit = limit;} + void setOffset(unsigned long offset) { m_offset = offset;} + + Api::Tizen::SortModePtr getSortMode() { return m_sortMode;} + Api::Tizen::FilterPtr getFilter() { return m_filter;} + unsigned long getLimit() { return m_limit;} + unsigned long getOffset() { return m_offset;} + void setConversations(const std::vector& conversations) { m_conversations = conversations; } + std::vector getConversations() { return m_conversations; } + void setFilterUsing(bool filter) { m_FilterUse = filter;} + bool isFilterUsing() { return m_FilterUse;} + + virtual void clearOnCancel() + { + } +}; +} +} +} +#endif + diff --git a/src/platform/API/Messaging/EventDeleteMessage.h b/src/platform/API/Messaging/EventDeleteMessage.h new file mode 100755 index 0000000..c601dc0 --- /dev/null +++ b/src/platform/API/Messaging/EventDeleteMessage.h @@ -0,0 +1,56 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file EventDeleteMessage.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef EVENTDELETEMESSAGE_H +#define EVENTDELETEMESSAGE_H + +#include + +#include +#include "IMessaging.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventDeleteMessage; + +typedef DPL::SharedPtr EventDeleteMessagePtr; + +class EventDeleteMessage : + public WrtDeviceApis::Commons::IEvent +{ + public: + + IMessagePtr msg; + + virtual void clearOnCancel() + { + } +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/EventDeleteMessages.h b/src/platform/API/Messaging/EventDeleteMessages.h new file mode 100755 index 0000000..f3c76d5 --- /dev/null +++ b/src/platform/API/Messaging/EventDeleteMessages.h @@ -0,0 +1,68 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file EventDeleteMessage.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef EVENTDELETEMESSAGES_H +#define EVENTDELETEMESSAGES_H + +#include +#include +#include +#include "IMessage.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventDeleteMessages; + +typedef DPL::SharedPtr EventDeleteMessagesPtr; + +class EventDeleteMessages : + public WrtDeviceApis::Commons::IEvent +{ + private: + Api::Tizen::FilterPtr m_filter; + public: + + IMessagePtr msg; + std::vector msgArray; + + public: + void setFilter(const Api::Tizen::FilterPtr& filter) { + m_filter = filter; + } + + Api::Tizen::FilterPtr getFilter() { + return m_filter; + } + + virtual void clearOnCancel() + { + } +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/EventGetConversationId.h b/src/platform/API/Messaging/EventGetConversationId.h new file mode 100755 index 0000000..ec31c55 --- /dev/null +++ b/src/platform/API/Messaging/EventGetConversationId.h @@ -0,0 +1,59 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * + * + * @file EventGetConversationId.h + * @author Kangsoo Lee (wpeter.lee@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef EVENT_GET_CONVERSATION_ID_H +#define EVENT_GET_CONVERSATION_ID_H + +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventGetConversationId; + +typedef DPL::SharedPtr EventGetConversationIdPtr; + +class EventGetConversationId : + public WrtDeviceApis::Commons::IEvent +{ +public: + void setConversationMsgPtr(const IMessagePtr msgPtr) { m_msgPtr = msgPtr;} + void setConversationId(int conversationId) { m_conversationId = conversationId;} + IMessagePtr getConversationMsgPtr() const { return m_msgPtr;} + int getConversationId() { return m_conversationId;} + EventGetConversationId() { } + ~EventGetConversationId(){} +private: + int m_conversationId; + IMessagePtr m_msgPtr; +}; +} +} +} +#endif + diff --git a/src/platform/API/Messaging/EventGetMessagingService.h b/src/platform/API/Messaging/EventGetMessagingService.h new file mode 100755 index 0000000..45a5c79 --- /dev/null +++ b/src/platform/API/Messaging/EventGetMessagingService.h @@ -0,0 +1,114 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author Dongjin Choi (milkelf.choi@samsung.com) + */ + +#ifndef WRTPLUGINS_API_GET_MESSAGING_SERVICE_EVENT_MESSAGING_H_ +#define WRTPLUGINS_API_GET_MESSAGING_SERVICE_EVENT_MESSAGING_H_ + +#include +#include +#include +#include + +#include "IMessagingService.h" +#include "IMessagingTypes.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { +class EventGetMessagingService: public WrtDeviceApis::Commons::IEvent +{ + +public: + static const int MESSAGING_SERVICE_MANAGER_EVENT_TYPE_ALL = 1; + static const int MESSAGING_SERVICE_MANAGER_EVENT_TYPE_ACCOUNT = 2; + +private: + + long m_accountID; + int m_messagingServiceType; + int m_eventType; + + std::vector< IMessagingServicePtr > m_messagingService; + +public: + void setAccountID(long value) { + //ToDo : check vailded Account, now temporary + m_accountID = value; + m_eventType = MESSAGING_SERVICE_MANAGER_EVENT_TYPE_ACCOUNT; //if set account, type will be changed as account type + } + + long getAccountID() const { + return m_accountID; + } + + void setEventType(int type) { + m_eventType = type; + } + + int getEventType() const{ + return m_eventType; + } + + void setMessagingServiceType(int type) { + m_messagingServiceType = type; + } + + int getMessagingServiceType() const { + return m_messagingServiceType; + } + + void setMessagingServicesRef(const std::vector< IMessagingServicePtr > &msgServices) + { + m_messagingService = msgServices; + } + + std::size_t getNumberOfMessagingService() + { + return m_messagingService.size(); + } + + IMessagingServicePtr getMessagingService(std::size_t index) + { + if (index >= m_messagingService.size() || m_messagingService.size() == 0) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + return m_messagingService[index]; + } + + std::vector getMessagingServices() + { + return m_messagingService; + } + + EventGetMessagingService() + { + m_accountID = -1, + m_eventType = MESSAGING_SERVICE_MANAGER_EVENT_TYPE_ALL; + } +}; + +typedef DPL::SharedPtr EventGetMessagingServicePtr; + +} // Api +} // WrtPlugins +} +#endif //WRTPLUGINS_API_GET_MESSAGING_SERVICE_EVENT_MESSAGING_H_ \ No newline at end of file diff --git a/src/platform/API/Messaging/EventMessageReceived.cpp b/src/platform/API/Messaging/EventMessageReceived.cpp new file mode 100755 index 0000000..b4ef2c4 --- /dev/null +++ b/src/platform/API/Messaging/EventMessageReceived.cpp @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ +#include "EventMessageReceived.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +EventMessageReceived::~EventMessageReceived() +{ +} + +IMessagePtr EventMessageReceived::getMessage() const +{ + return m_message; +} + +void EventMessageReceived::setMessage(const IMessagePtr& message) +{ + m_message = message; +} + +IConversationPtr EventMessageReceived::getConversation() const +{ + return m_conversation; +} + +void EventMessageReceived::setConversation(const IConversationPtr& converation) +{ + m_conversation = converation; +} + +IMessageFolderPtr EventMessageReceived::getMessageFolder() const +{ + return m_messagefolder; +} + +void EventMessageReceived::setMessageFolder(const IMessageFolderPtr& messagefolder) +{ + m_messagefolder = messagefolder; +} + +void EventMessageReceived::setMsg_Event_Type(Msg_EventType state) +{ + m_msg_event_type = state; +} + +} +} // Api +} // WrtPlugins diff --git a/src/platform/API/Messaging/EventMessageReceived.h b/src/platform/API/Messaging/EventMessageReceived.h new file mode 100755 index 0000000..a9a6d8d --- /dev/null +++ b/src/platform/API/Messaging/EventMessageReceived.h @@ -0,0 +1,78 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file EventReceiveMessage.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef WRTPLUGINS_MESSAGING_EVENTMESSAGERECEIVED_H_ +#define WRTPLUGINS_MESSAGING_EVENTMESSAGERECEIVED_H_ + +#include +#include +#include "IMessage.h" +#include "IConversation.h" +#include "IMessageFolder.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventMessageReceived : public WrtDeviceApis::Commons::ListenerEvent< + EventMessageReceived> +{ + public: + typedef enum + { + MSG_ADDED = 0, + MSG_UPDATED = 1, + MSG_DELETED = 2, + MSG_MULTIPLE = 3, + } Msg_EventType; + + virtual ~EventMessageReceived(); + + IMessagePtr getMessage() const; + IConversationPtr getConversation() const; + IMessageFolderPtr getMessageFolder() const; + + void setMessage(const IMessagePtr& message); + void setConversation(const IConversationPtr &conversation); + void setMessageFolder(const IMessageFolderPtr &messagefolder); + + void setMsg_Event_Type(Msg_EventType state); + Msg_EventType getMsg_Event_Type() { return m_msg_event_type;} + + + private: + IConversationPtr m_conversation; + IMessagePtr m_message; + IMessageFolderPtr m_messagefolder; + Msg_EventType m_msg_event_type; + +}; + +typedef DPL::SharedPtr EventMessageReceivedPtr; +} // Api +} // WrtPlugins +} +#endif // WRTPLUGINS_MESSAGING_EVENTMESSAGERECEIVED_H_ diff --git a/src/platform/API/Messaging/EventMessagingService.h b/src/platform/API/Messaging/EventMessagingService.h new file mode 100755 index 0000000..057cf2c --- /dev/null +++ b/src/platform/API/Messaging/EventMessagingService.h @@ -0,0 +1,102 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author Dongjin Choi (milkelf.choi@samsung.com) + */ + +#ifndef WRTPLUGINS_API_MESSAGING_SERVICE_EVENT_H_ +#define WRTPLUGINS_API_MESSAGING_SERVICE_EVENT_H_ + +#include +#include +#include "MessageProperties.h" + +#include "IMessage.h" +#include "IAttachment.h" +#include "IMessagingService.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventMessagingService; + +class EventMessagingService: public WrtDeviceApis::Commons::IEvent { + +public: + static const int MESSAGING_SERVICE_EVENT_TYPE_SEND_MESSAGE = 1; + static const int MESSAGING_SERVICE_EVENT_TYPE_LOAD_MESSAGE_BODY = 2; + static const int MESSAGING_SERVICE_EVENT_TYPE_LOAD_MESSAGE_ATTACHMENT = 3; + static const int MESSAGING_SERVICE_EVENT_TYPE_SYNC = 4; //now, I have no idea about sync. + static const int MESSAGING_SERVICE_EVENT_TYPE_SYNC_FOLDER = 5; + +private: + + MessagingPropertiesPtr m_messagingPropsPtr; + int m_eventType; + + + //now temporary + //IMessagePtr m_message; +public: + int getEventType() const{ + return m_eventType; + } + + void setEventType(int type) { + m_eventType = type; + } + + void setMessageProperties(MessagingPropertiesPtr msgProps) + { + m_messagingPropsPtr = msgProps; + } + + MessagingPropertiesPtr getMessageProperties() + { + return m_messagingPropsPtr; + } + + IMessagePtr m_message; + + IAttachmentPtr m_attachment; + + IMessagingServicePtr m_messagingService; + + int opId; + + std::string m_folder_name; + + int m_sync_account_id; //account ID + int m_sync_folder_id; // folder ID + int m_sync_limit; //limit + + EventMessagingService() + { + m_eventType = MESSAGING_SERVICE_EVENT_TYPE_SEND_MESSAGE; //default value. + } + +}; + +typedef DPL::SharedPtr EventMessagingServicePtr; + +} // Api +} // WrtPlugins +} +#endif //WRTPLUGINS_API_MESSAGING_SERVICE_EVENT_H_ + diff --git a/src/platform/API/Messaging/EventMessagingStorage.h b/src/platform/API/Messaging/EventMessagingStorage.h new file mode 100755 index 0000000..94236c6 --- /dev/null +++ b/src/platform/API/Messaging/EventMessagingStorage.h @@ -0,0 +1,100 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author Dongjin Choi (milkelf.choi@samsung.com) + */ + +#ifndef WRTPLUGINS_API_ADD_DRAFT_MESSAGE_EVENT_MESSAGINGSTORAGE_H_ +#define WRTPLUGINS_API_ADD_DRAFT_MESSAGE_EVENT_MESSAGINGSTORAGE_H_ + +//#include "PluginTempleteProperties.h" + +#include +#include +#include // later MAY be changed to IMessagingStorage.h + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventMessagingStorage: public WrtDeviceApis::Commons::IEvent { + +public: + + static const int MESSAGING_STORAGE_EVENT_UNKNOWN = -1; + static const int MESSAGING_STORAGE_EVENT_ADD_DRAFT_MESSAGE = 1; + static const int MESSAGING_STORAGE_EVENT_QUERY_MESSAGES = 2; + static const int MESSAGING_STORAGE_EVENT_DELETE_MESSAGES = 3; + static const int MESSAGING_STORAGE_EVENT_UPDATE_MESSAGES = 4; + static const int MESSAGING_STORAGE_EVENT_QUERY_CONVERSATIONS = 5; + static const int MESSAGING_STORAGE_EVENT_DELETE_CONVERSATIONS = 6; + static const int MESSAGING_STORAGE_EVENT_QUERYFOLDERS = 7; +// static const int MESSAGING_STORAGE_EVENT_ON_MESSAGING_STORAGE_CHANGES = 8; + + +// input parameters +//MessageFilterPtr messageFilter; +std::vector messageTypes; +std::vector folderTypes; +// AccountID to be added for email +// Message to be added for addDraftMessage +// tempolary IMessagePtr msg; + +private: + +/* + long m_accountID; +*/ + int m_eventType; + + +public: +/* + void setAccountID(long value) { + //ToDo : check vailded Account, now temporary + m_accountID = value; + m_eventType = MESSAGING_SERVICE_MANAGER_EVENT_TYPE_ACCOUNT; //if set account, type will be changed as account type + } + + long getAccountID() const { + return m_accountID; + } + +*/ +void setEventType(int type){ + m_eventType = type; +} + +int getEventType(){ + return m_eventType; + } + + + EventMessagingStorage() + { +// m_accountID = -1, + m_eventType = MESSAGING_STORAGE_EVENT_UNKNOWN; + } +}; + +typedef DPL::SharedPtr EventMessagingStoragePtr; + +} // Api +} // WrtPlugins +} +#endif //WRTPLUGINS_API_GET_MESSAGING_SERVICE_EVENT_MESSAGING_H_ \ No newline at end of file diff --git a/src/platform/API/Messaging/EventOnSendingFailed.h b/src/platform/API/Messaging/EventOnSendingFailed.h new file mode 100755 index 0000000..cbb7268 --- /dev/null +++ b/src/platform/API/Messaging/EventOnSendingFailed.h @@ -0,0 +1,76 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * @file EventOnSendingFailed.h + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef EVENTONSENDINGFAILED_H_ +#define EVENTONSENDINGFAILED_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +/* + * + */ +class EventOnSendingFailed : public WrtDeviceApis::Commons::ListenerEvent +{ + public: + typedef enum + { + NO_NETWORKING, + NO_CONNECTION, + BAD_PAYLOAD, + UNKNOWN + } ErrorCode; + + EventOnSendingFailed() + { + } + + void setError(ErrorCode error) + { + m_error = error; + } + + ErrorCode getError() const + { + return m_error; + } + + private: + ErrorCode m_error; +}; + +typedef DPL::SharedPtr EventOnSendingFailedPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter +EventOnSendingFailedEmitter; +typedef DPL::SharedPtr +EventOnSendingFailedEmitterPtr; +} // Api +} // WrtPlugins +} +#endif /* EVENTONSENDINGFAILED_H_ */ diff --git a/src/platform/API/Messaging/EventQueryConversations.h b/src/platform/API/Messaging/EventQueryConversations.h new file mode 100755 index 0000000..898dec4 --- /dev/null +++ b/src/platform/API/Messaging/EventQueryConversations.h @@ -0,0 +1,80 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * + * + * @file EventQueryConversatioin.h + * @author Kangsoo Lee (wpeter.lee@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef EVENT_QUERY_CONVERSATIONS_H +#define EVENT_QUERY_CONVERSATIONS_H + +#include +#include +#include +#include + +#include "IMessage.h" +#include "IConversation.h" +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventQueryConversations; + +typedef DPL::SharedPtr EventQueryConversationsPtr; + +class EventQueryConversations : + public WrtDeviceApis::Commons::IEvent +{ + public: + void setSortMode(Api::Tizen::SortModePtr sortMode) { m_sortMode = sortMode;} + void setFilter(Api::Tizen::FilterPtr filter) { m_filter = filter;} + void setLimit(unsigned long limit) { m_limit = limit;} + void setOffset(unsigned long offset) { m_offset = offset;} + void addConversations(std::vector conv) + { m_conversations.insert(m_conversations.end(), conv.begin(), conv.end());} + Api::Tizen::SortModePtr getSortMode() { return m_sortMode;} + Api::Tizen::FilterPtr getFilter() { return m_filter;} + unsigned long getLimit() { return m_limit;} + unsigned long getOffset() { return m_offset;} + std::vector getConversatioins() { return m_conversations;} + + virtual void clearOnCancel() + { + } + +private: + // input parameters + Api::Tizen::SortModePtr m_sortMode; + Api::Tizen::FilterPtr m_filter; + unsigned long m_limit; + unsigned long m_offset; + //output parameter + std::vector m_conversations; + +}; +} +} +} +#endif + diff --git a/src/platform/API/Messaging/EventQueryFolders.h b/src/platform/API/Messaging/EventQueryFolders.h new file mode 100755 index 0000000..3690132 --- /dev/null +++ b/src/platform/API/Messaging/EventQueryFolders.h @@ -0,0 +1,82 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file EventQueryFolders.h + * @author Oy Kwon (sirot.kwon@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef EVENTQUERYFOLDERS_H +#define EVENTQUERYFOLDERS_H + +#include +#include +#include +#include "IMessage.h" +#include "IMessageFolder.h" +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventQueryFolders; + +typedef DPL::SharedPtr EventQueryFoldersPtr; + +class EventQueryFolders : + public WrtDeviceApis::Commons::IEvent +{ + private: + // input parameters + Api::Tizen::FilterPtr m_filter; + int m_accountId; + //output parameter + std::vector m_folders; + + public: + EventQueryFolders() : m_accountId(-1){ + } + + void setFilter(Api::Tizen::FilterPtr filter) { m_filter = filter;} + void addFolders(std::vector folder) + { m_folders.insert(m_folders.end(), folder.begin(), folder.end());} + Api::Tizen::FilterPtr getFilter() { return m_filter;} + std::vector getFolders() { return m_folders;} + + void setAccountId(int accountId){ + m_accountId = accountId; + } + int getAccountId(){ + return m_accountId; + } + + virtual void clearOnCancel() + { + } + + + +}; +} +} +} +#endif + diff --git a/src/platform/API/Messaging/EventQueryMessages.h b/src/platform/API/Messaging/EventQueryMessages.h new file mode 100755 index 0000000..bb6179e --- /dev/null +++ b/src/platform/API/Messaging/EventQueryMessages.h @@ -0,0 +1,103 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file EventQueryMessage.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef EVENTQUERYMESSAGES_H +#define EVENTQUERYMESSAGES_H + +#include +#include +#include +#include + +#include "IMessage.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventQueryMessages; + +typedef DPL::SharedPtr EventQueryMessagesPtr; + +class EventQueryMessages : + public WrtDeviceApis::Commons::IEvent +{ + private: + Api::Tizen::FilterPtr m_filter; + Api::Tizen::SortModePtr m_sortMode; + long m_limit; + long m_offset; + + public: + EventQueryMessages() : m_limit(0), m_offset(0){ + } + // input parameters + std::vector messageTypes; + std::vector folderTypes; + + //output parameter + std::vector msgs; + + public: + void setFilter(const Api::Tizen::FilterPtr& filter) { + m_filter = filter; + } + + Api::Tizen::FilterPtr getFilter() { + return m_filter; + } + + void setSortMode(const Api::Tizen::SortModePtr& sortMode) { + m_sortMode = sortMode; + } + + Api::Tizen::SortModePtr getSortMode() { + return m_sortMode; + } + + void setLimit(long limit){ + m_limit = limit; + } + + long getLimit(){ + return m_limit; + } + + void setOffset(long offset){ + m_offset = offset; + } + + long getOffset(){ + return m_offset; + } + + virtual void clearOnCancel() + { + } +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/EventSendMessage.h b/src/platform/API/Messaging/EventSendMessage.h new file mode 100755 index 0000000..9c21354 --- /dev/null +++ b/src/platform/API/Messaging/EventSendMessage.h @@ -0,0 +1,88 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file EventSendMessage.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef EVENTSENDMESSAGE_H +#define EVENTSENDMESSAGE_H + +#include + +#include +#include "IMessagingService.h" +#include "IMessaging.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventSendMessage; + +typedef DPL::SharedPtr EventSendMessagePtr; + +class EventSendMessage : + public WrtDeviceApis::Commons::IEvent +{ + public: + + IMessagePtr msg; + IMessagingServicePtr m_messagingService; //messaging service. + + std::vector m_successRecipients; //sucess + std::vector m_failRecipients; //fail + bool store; + int opId; + + void setRecipient(const std::string &recipient) + { + m_recipient = recipient; + } + + std::string getRecipient() const + { + return m_recipient; + } + + virtual void clearOnCancel() + { + } + + void setSendCallbackPerRecipient(bool sendCallbackPerRecipient) + { + m_sendCallbackPerRecipient = sendCallbackPerRecipient; + } + + bool getSendCallbackPerRecipient() const + { + return m_sendCallbackPerRecipient; + } + + private: + std::string m_recipient; + bool m_sendCallbackPerRecipient; + +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/EventUpdateMessage.h b/src/platform/API/Messaging/EventUpdateMessage.h new file mode 100755 index 0000000..3ec165c --- /dev/null +++ b/src/platform/API/Messaging/EventUpdateMessage.h @@ -0,0 +1,59 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file EventUpdateMessage.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef EVENTUPDATEMESSAGE_H +#define EVENTUPDATEMESSAGE_H + +#include + +#include +#include "IMessaging.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventUpdateMessage; + +typedef DPL::SharedPtr EventUpdateMessagePtr; + +class EventUpdateMessage : + public WrtDeviceApis::Commons::IEvent +{ + public: + + IMessagePtr msg; + + virtual void clearOnCancel() + { + } +}; + +typedef WrtDeviceApis::Commons::EventAnswerReceiver +EventUpdateMessageAnswerReceiver; +} +} +} +#endif diff --git a/src/platform/API/Messaging/EventUpdateMessages.h b/src/platform/API/Messaging/EventUpdateMessages.h new file mode 100755 index 0000000..9abe9ad --- /dev/null +++ b/src/platform/API/Messaging/EventUpdateMessages.h @@ -0,0 +1,57 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file EventUpdateMessages.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef EVENTUPDATEMESSAGES_H +#define EVENTUPDATEMESSAGES_H + +#include +#include +#include +#include "IMessage.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventUpdateMessages; + +typedef DPL::SharedPtr EventUpdateMessagesPtr; + +class EventUpdateMessages : + public WrtDeviceApis::Commons::IEvent +{ + public: + + IMessagePtr msg; + std::vector msgArray; + + virtual void clearOnCancel() + { + } +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/FolderFilterValidator.cpp b/src/platform/API/Messaging/FolderFilterValidator.cpp new file mode 100644 index 0000000..08d44b6 --- /dev/null +++ b/src/platform/API/Messaging/FolderFilterValidator.cpp @@ -0,0 +1,122 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * FolderFilterValidator.cpp + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#include "FolderFilterValidator.h" +#include "FolderFilterValidatorFactory.h" + +#include +#include "log.h" + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + FolderFilterValidator::FolderFilterValidator(PropertyStructArray properties, + MatchFlagStrArray matchFlag, Api::Tizen::PrimitiveType idType):FilterValidator(properties, matchFlag){ + m_isAccountIdSetted = false; + + initMatchFlagVectors(); + initAttributeAndMatchFlagsMap(); + } + + FolderFilterValidator::~FolderFilterValidator(){ + } + + void FolderFilterValidator::initMatchFlagVectors(){ + m_accountIdMatchFlagVec.push_back(FolderFilterValidatorFactory::MATCH_EXACTLY); + m_folderPathMatchFlagVec.push_back(FolderFilterValidatorFactory::MATCH_EXACTLY); + } + + void FolderFilterValidator::initAttributeAndMatchFlagsMap(){ + m_attributeAndMatchFlagsMap[FolderFilterValidatorFactory::ATTRIBUTE_ACCOUNTID] = m_accountIdMatchFlagVec; + m_attributeAndMatchFlagsMap[FolderFilterValidatorFactory::ATTRIBUTE_FOLDERPATH] = m_folderPathMatchFlagVec; + } + + bool FolderFilterValidator::validateAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth){ + bool retVal = false; + return retVal; + } + + bool FolderFilterValidator::vectorContains(std::vector& vec, std::string& value){ + std::vector::iterator it; + for(it=vec.begin(); itbegin(); iter!=values->end(); iter++){ + AnyPtr value = *iter; + if(validateAttributeEach(attrName, value, matchFlag, depth) == false){ + MsgLogWanning(">>>[Warning] attrName:[" << attrName << "] is invalid value:[" << value->toString() << "]"); + return false; + } + } + LogDebug("## 001 ##"); + retBool = FilterValidator::validateAttribute(attrName, values, matchFlag, caseSensitive, depth); + LogDebug("## 002 ##"); + LogDebug(">>> retBool:" << retBool); + return retBool; + } + + bool FolderFilterValidator::validateAttributeEach(std::string& attrName, Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth){ + LogDebug("<<< attrName:[" << attrName << "], value:[" << value->toString() << "]"); + + if(attrName.compare(FolderFilterValidatorFactory::ATTRIBUTE_ACCOUNTID)==0){ + LogDebug("<<< m_isAccountIdSetted :[" << m_isAccountIdSetted << "]"); + if(m_isAccountIdSetted == true){ + LogError(">>> [ERROR] duplicated account :[" << attrName << "], value:[" << + value->toString()<< "]"); + return false; + }else{ + m_isAccountIdSetted = true; + } + } + + LogDebug("## 001 ##"); + std::vector vec = m_attributeAndMatchFlagsMap.find(attrName)->second; + LogDebug("## 002 ##"); + + if(vectorContains(vec, matchFlag)==false){ + MsgLogWanning(">>>[Waning]MatchFlag check fail unsupported flag:[" << matchFlag << "] for Attribute:[" << attrName << "]"); + return false; + } + LogDebug("## 003 ##"); + return true; + } + + } + } + +} diff --git a/src/platform/API/Messaging/FolderFilterValidator.h b/src/platform/API/Messaging/FolderFilterValidator.h new file mode 100644 index 0000000..2a50dd2 --- /dev/null +++ b/src/platform/API/Messaging/FolderFilterValidator.h @@ -0,0 +1,72 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * FolderFilterValidator.h + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#ifndef FOLDERFILTERVALIDATOR_H_ +#define FOLDERFILTERVALIDATOR_H_ + +#include +#include + +namespace TizenApis { + + namespace Platform { + + namespace Messaging { + + class FolderFilterValidator: public Api::Tizen::FilterValidator { + private: + bool m_isAccountIdSetted; + + std::vector m_accountIdMatchFlagVec; + std::vector m_folderPathMatchFlagVec; + + std::map > m_attributeAndMatchFlagsMap; + + public: + FolderFilterValidator(Api::Tizen::PropertyStructArray properties, + Api::Tizen::MatchFlagStrArray matchFlag, Api::Tizen::PrimitiveType idType); + + virtual ~FolderFilterValidator(); + + // validate AttributeRangeFilter + virtual bool validateAttributeRange(std::string& attrName, + Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth=0); + + virtual bool validateAttribute(std::string& attrName, + Api::Tizen::AnyArrayPtr& values, std::string& matchFlag, bool caseSensitive, int depth=0); + + protected: + bool validateAttributeEach(std::string& attrName,Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth); + + private : + void initMatchFlagVectors(); + void initAttributeAndMatchFlagsMap(); + + bool vectorContains(std::vector& vec, std::string& value); + + }; + + typedef DPL::SharedPtr FolderFilterValidatorPtr; + } + } +} +#endif /* MESSAGEFILTERVALIDATOR_H_ */ diff --git a/src/platform/API/Messaging/FolderFilterValidatorFactory.cpp b/src/platform/API/Messaging/FolderFilterValidatorFactory.cpp new file mode 100644 index 0000000..ec60334 --- /dev/null +++ b/src/platform/API/Messaging/FolderFilterValidatorFactory.cpp @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * FolderFilterValidatorFactory.cpp + * + * Created on: 2011. 10. 27. + * Author: sangtai + */ + +#include "FolderFilterValidatorFactory.h" + +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + const std::string FolderFilterValidatorFactory::ATTRIBUTE_ACCOUNTID = "accountid"; + const std::string FolderFilterValidatorFactory::ATTRIBUTE_FOLDERPATH = "path"; + + std::string FolderFilterValidatorFactory::MATCH_EXACTLY = "EXACTLY"; + std::string FolderFilterValidatorFactory::MATCH_CONTAINS = "CONTAINS"; + std::string FolderFilterValidatorFactory::MATCH_STARTSWITH = "STARTSWITH"; + std::string FolderFilterValidatorFactory::MATCH_ENDSWITH = "ENDSWITH"; +// std::string FolderFilterValidatorFactory::MATCH_CASESENSITIVE = "CASESENSITIVE"; + + //TODO change to constant + static PropertyStructArray properties = + { + {"accountid", Api::Tizen::PrimitiveType_String}, + {"path", Api::Tizen::PrimitiveType_String}, + {0, Api::Tizen::PrimitiveType_Notype} + }; + + static MatchFlagStrArray matchFlag{ + "EXACTLY", + "CONTAINS", + "STARTSWITH", + "ENDSWITH", +// "MATCH_CASESENSITIVE", + 0 + }; + + FolderFilterValidatorPtr FolderFilterValidatorFactory::getFolderFilterValidator() + { + FolderFilterValidatorPtr theInstance = + FolderFilterValidatorPtr(new FolderFilterValidator(properties, matchFlag, Api::Tizen::PrimitiveType_Int)); + + return theInstance; + } + + } + } //naspace Platform +} //naspace WrtPlugins diff --git a/src/platform/API/Messaging/FolderFilterValidatorFactory.h b/src/platform/API/Messaging/FolderFilterValidatorFactory.h new file mode 100644 index 0000000..18383b2 --- /dev/null +++ b/src/platform/API/Messaging/FolderFilterValidatorFactory.h @@ -0,0 +1,57 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * MessagingFilterValidatorFactory.h + * + * Created on: 2011. 10. 27. + * Author: sangtai + */ + +#ifndef FOLDERFILTERVALIDATORFACTORY_H_ +#define FOLDERFILTERVALIDATORFACTORY_H_ + +#include +#include "FolderFilterValidator.h" + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + class FolderFilterValidatorFactory { + private: + FolderFilterValidatorFactory() + { + } + + public: + static FolderFilterValidatorPtr getFolderFilterValidator(); + + public: + static const std::string ATTRIBUTE_ACCOUNTID; + static const std::string ATTRIBUTE_FOLDERPATH; + + static std::string MATCH_EXACTLY; + static std::string MATCH_CONTAINS; + static std::string MATCH_STARTSWITH; + static std::string MATCH_ENDSWITH; + static std::string MATCH_CASESENSITIVE; + }; + + } + } //Platform +} + +#endif diff --git a/src/platform/API/Messaging/From.cpp b/src/platform/API/Messaging/From.cpp new file mode 100755 index 0000000..9affacb --- /dev/null +++ b/src/platform/API/Messaging/From.cpp @@ -0,0 +1,69 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file From.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "From.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +From::From() : + m_from(""), + m_validFrom(false) +{ +} + +From::~From() +{ +} + +void From::setFrom(const std::string& value) +{ + m_from = value; + m_validFrom = false; +} + +std::string From::getFrom() const +{ + return m_from; +} + +const std::string& From::getFromRef() const +{ + return m_from; +} + +void From::setFromValidity(bool val) +{ + m_validFrom = val; +} + +bool From::getFromValidity() const +{ + return m_validFrom; +} +} +} +} diff --git a/src/platform/API/Messaging/From.h b/src/platform/API/Messaging/From.h new file mode 100755 index 0000000..b66f4b8 --- /dev/null +++ b/src/platform/API/Messaging/From.h @@ -0,0 +1,77 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file From.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef FROM_H +#define FROM_H + +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class From +{ + private: // fields + + /** + * from value + */ + std::string m_from; + + /** + * information if abstract message from has been changed and need update + * in low level + */ + bool m_validFrom; + + public: // methods + + From(); + + virtual ~From(); + + /** + * setter of from value + */ + void setFrom(const std::string& value); + + /** + * getter of from value + */ + std::string getFrom() const; + + const std::string& getFromRef() const; + + void setFromValidity(bool val); + + bool getFromValidity() const; +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/IAttachment.cpp b/src/platform/API/Messaging/IAttachment.cpp new file mode 100755 index 0000000..4260ceb --- /dev/null +++ b/src/platform/API/Messaging/IAttachment.cpp @@ -0,0 +1,182 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IAttachment.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include +#include +#include +#include "IAttachment.h" + +extern "C" { +#include +#include +} + +using namespace WrtDeviceApis::Commons; +using namespace std; + +//-------------------------------------------------------------------------- +namespace TizenApis { +namespace Api { +namespace Messaging { + +IAttachment::IAttachment() : + m_validAttachment(false) +{ +} + +void IAttachment::init(const string& fullPath, + bool isVirtualPath) +{ + Try + { + struct stat buffer; + std::string l_fullPath; + LogDebug("FULL Path : " << fullPath); + + if (isVirtualPath) { + LogDebug("translating path"); + l_fullPath = getRealPath(fullPath); + } else { + l_fullPath = fullPath; + } + LogDebug("real path " << l_fullPath); + + char buff[PATH_MAX + 1]; + if (NULL == realpath(l_fullPath.c_str(), buff)) { + std::string errnoString = DPL::GetErrnoString(); + LogError("get full path problem " << errnoString); + ThrowMsg(InvalidArgumentException, + "get full path problem " << errnoString); + } + + if (-1 == lstat(buff, &buffer)) { + LogError("Attachment file not exist"); + ThrowMsg(InvalidArgumentException, "Attachment file not exist"); + } + + if (!S_ISREG(buffer.st_mode)) { + LogError("Attachment file not exist"); + ThrowMsg(InvalidArgumentException, "Attachment file not exist"); + } + m_fileSize = buffer.st_size; + m_attachFullPath = l_fullPath; + makeShortName(); + m_isCreatedProperly = true; + + } + + Catch(WrtDeviceApis::Commons::Exception) { + LogError("attachment not created properly"); + m_isCreatedProperly = false; + } +} + +IAttachment::~IAttachment() +{ + LogDebug("enter"); +} + +string IAttachment::getShortName() const +{ + return m_attachShortName; +} + +string IAttachment::getFullPath() const +{ + return m_attachFullPath; +} + +unsigned int IAttachment::getFileSize() const +{ + return m_fileSize; +} + +std::string IAttachment::getMimeType() const +{ + return m_mimeType; +} + +void IAttachment::setMimeType(const std::string &mimeType) +{ + m_mimeType = mimeType; +} + +Api::Messaging::IMessagePtr IAttachment::getMessage() const +{ + return m_message; +} + +void IAttachment::setMessage(const Api::Messaging::IMessagePtr& message) +{ + m_message = message; +} + +int IAttachment::getAttachmentID() const +{ + return m_attachmentID; +} + +void IAttachment::setAttachmentID(int id) +{ + m_attachmentID = id; +} + +bool IAttachment::getDownloaded() const +{ + return m_isDownloaded; +} + +void IAttachment::setDownloaded(bool downloaded) +{ + m_isDownloaded = downloaded; +} + +bool IAttachment::getIsCreatedProperly() const +{ + return m_isCreatedProperly; +} + +void IAttachment::rename(const string& newName) +{ + // path for attachment is still not changed + m_attachShortName = newName; + m_validAttachment = false; +} + +void IAttachment::makeShortName() +{ + size_t pos; + // find position of last occurence of / sign (get only file name from all path + pos = m_attachFullPath.find_last_of("/"); + if ((pos + 1) >= m_attachFullPath.size()) { + LogError("Problem with short name creation"); + Throw(InvalidArgumentException); + } + m_attachShortName = m_attachFullPath.substr(pos + 1); +} +} +} +} diff --git a/src/platform/API/Messaging/IAttachment.h b/src/platform/API/Messaging/IAttachment.h new file mode 100755 index 0000000..999f7c0 --- /dev/null +++ b/src/platform/API/Messaging/IAttachment.h @@ -0,0 +1,158 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IAttachment.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef IATTACHMENT_H +#define IATTACHMENT_H + +#include +#include +#include "IMessage.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class IAttachment; +typedef DPL::SharedPtr IAttachmentPtr; + +//-------------------------------------------------------------------------- + +class IAttachment +{ + protected: // fields + + /** + * value of attachment full path name + */ + std::string m_attachFullPath; + + /** + * value of attachment short name used to display in message + */ + std::string m_attachShortName; + + /** + * value of attachment file size + */ + unsigned int m_fileSize; + + /** + * value of attachment mime type + */ + std::string m_mimeType; + + /** + * information if abstract message attachment has been changed and need + * update in low level + * only name may be changed, not path + */ + bool m_validAttachment; + + bool m_isCreatedProperly; + + bool m_isDownloaded; + + int m_attachmentID; // attachment ID from email service. + + int m_nth; // attachment order index, 1 base. + + IMessagePtr m_message; //message ptr + + public: // methods + + explicit IAttachment(); + + void init(const std::string& fullPath, + bool isVirtualPath); + + virtual ~IAttachment(); + + /** + * getter of attachment name (only name without path) value + */ + std::string getShortName() const; + + /** + * getter of attachment name (full path) value + */ + std::string getFullPath() const; + + /** + * getter of attachment size + */ + unsigned int getFileSize() const; + + /** + * getter of attachment mime type + */ + std::string getMimeType() const; + + /** + * setter of attachment mime type + */ + void setMimeType(const std::string &mimeType); + + Api::Messaging::IMessagePtr getMessage() const; + + void setMessage(const Api::Messaging::IMessagePtr& message); + + /** + * getter of attachment valid + */ + bool getIsCreatedProperly() const; + + /** + * rename short name value of attachment + */ + void rename(const std::string& newName); + + + void setAttachmentID(int id); + + int getAttachmentID() const; + + void setDownloaded(bool downloaded); + + bool getDownloaded() const; + + int getNth() + { + return m_nth; + } + + void setNth(int nth) + { + m_nth = nth; + } + private: + + void makeShortName(); + + virtual std::string getRealPath(const std::string &path) const = 0; +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/IBinarySms.cpp b/src/platform/API/Messaging/IBinarySms.cpp new file mode 100755 index 0000000..b8e284b --- /dev/null +++ b/src/platform/API/Messaging/IBinarySms.cpp @@ -0,0 +1,45 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IBinarySms.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "IBinarySms.h" +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +IBinarySms::IBinarySms(const std::string& id) : + IMessage(BINARYSMS, id) +{ + LogDebug("enter"); +} + +IBinarySms::~IBinarySms() +{ + LogDebug("enter"); +} +} +} +} diff --git a/src/platform/API/Messaging/IBinarySms.h b/src/platform/API/Messaging/IBinarySms.h new file mode 100755 index 0000000..2631b1e --- /dev/null +++ b/src/platform/API/Messaging/IBinarySms.h @@ -0,0 +1,55 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IBinarySms.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef IBINARYSMS_H +#define IBINARYSMS_H + +#include "IMessage.h" +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class IBinarySms; +typedef DPL::SharedPtr IBinarySmsPtr; + +class IBinarySms : + virtual public IMessage +{ + public: // fields + + public: // methods + + explicit IBinarySms(const std::string& id = ""); + + virtual ~IBinarySms(); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/IConversation.h b/src/platform/API/Messaging/IConversation.h new file mode 100755 index 0000000..9c22f25 --- /dev/null +++ b/src/platform/API/Messaging/IConversation.h @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** +* @file Conversation.h +* @author Kangsoo Lee (wpeter.lee@samsung.com) +* @version 0.1 +*/ + +#ifndef ICONVERSATION_H +#define ICONVERSATION_H + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class IConversation; +typedef DPL::SharedPtr IConversationPtr; + + +class IConversation +{ +public: + IConversation() {} + virtual ~IConversation() {}; + // getter + virtual unsigned int getId() = 0; + virtual unsigned short getType() = 0; + virtual time_t getTime() = 0; + virtual unsigned long getMessageCount() = 0; + virtual unsigned long getUnreadMessages() = 0; + virtual std::string getPreview() = 0; + virtual std::string getSubject() = 0; + virtual bool getRead() = 0; + virtual std::string getFrom() = 0; + virtual std::vector getTo() = 0; + virtual std::vector getCC() = 0; + virtual std::vector getBCC() = 0; + virtual unsigned int getLastMessageId() = 0; + virtual bool getResult() = 0; + +#if 0 +private: + + // setter + virtual void setId(unsigned int id) = 0; + virtual void setType(unsigned short type) = 0; + virtual void setTime(time_t time) = 0; + virtual void setMessageCount(unsigned long messageCount) = 0; + virtual void setUnreadMessages(unsigned long unreadMessages) = 0; + virtual void setPreview(unsigned long unreadMessages) = 0; + virtual void setRead(bool read) = 0; + virtual void setFrom(std::string from) = 0; + virtual void setTo(std::vector to) = 0; + virtual void setCC(std::vector cc) = 0; + virtual void setBCC(std::vector bcc) = 0; + virtual void setLastMessageId(unsigned int id) = 0; +#endif +}; +} +} +} + +#endif + diff --git a/src/platform/API/Messaging/IEmail.cpp b/src/platform/API/Messaging/IEmail.cpp new file mode 100755 index 0000000..34bddf8 --- /dev/null +++ b/src/platform/API/Messaging/IEmail.cpp @@ -0,0 +1,65 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IEmail.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "IEmail.h" +#include + +using namespace std; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +IEmail::IEmail(const string& id) : IMessage(EMAIL, id) +{ + LogInfo("enter"); +} + +IEmail::~IEmail() +{ + LogInfo("enter"); +} + +IEmail & IEmail::operator <<(const VirtualMessage& msg) +{ + setBody(msg.getBodyRef()); + setFolderType(msg.getCurrentFolder()); + setCurrentUserFolder(msg.getCurrentUserFolder()); + setFrom(msg.getFromRef()); + setDateTime(msg.getDateTime()); + setSourceAddress(msg.getSourceAddress()); + setToRecipients(msg.getToRecipients()); +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + setAttachments(msg.getAttachments()); +#endif + setBccRecipients(msg.getBccRecipients()); + setCcRecipients(msg.getCcRecipients()); + setSubject(msg.getSubjectRef()); + + return *this; +} +} +} +} diff --git a/src/platform/API/Messaging/IEmail.h b/src/platform/API/Messaging/IEmail.h new file mode 100755 index 0000000..4b48394 --- /dev/null +++ b/src/platform/API/Messaging/IEmail.h @@ -0,0 +1,93 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * + * + * @file IEmail.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef IEMAIL_H +#define IEMAIL_H + +#include +#include +#include "VirtualMessage.h" +#include "IMessage.h" +#include "Subject.h" +#include "ToRecipient.h" +#include "CcRecipient.h" +#include "BccRecipient.h" +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +#include "Attachments.h" +#endif + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class IEmail : virtual public IMessage, + public CcRecipient, + public BccRecipient +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + , + public Attachments +#endif +{ + public: + explicit IEmail(const std::string& id = ""); + + virtual ~IEmail(); + + IEmail & operator <<(const VirtualMessage& msg); + + void setHtmlBody(const std::string& htmlBody = "") + { + m_htmlBody = htmlBody; + } + + std::string getHtmlBody() const + { + return m_htmlBody; + } + + virtual int getAccountID() = 0; + virtual int getUID() = 0; + virtual int isBodyDownloaded() = 0; + + virtual int downloadBody() = 0; + virtual void downloadBodyCancel(int handle ) = 0; + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + virtual void downloadAttachment(const Api::Messaging::IAttachmentPtr& attachment) = 0; +#endif + +#if 0 + virtual void sync(int account_id); + virtual void sync_folder(int account_id, int folder_id); +#endif + private: + std::string m_htmlBody; //html body for Email. +}; + +typedef DPL::SharedPtr IEmailPtr; +} +} +} +#endif // IEMAIL_H + diff --git a/src/platform/API/Messaging/IEmailAccount.cpp b/src/platform/API/Messaging/IEmailAccount.cpp new file mode 100755 index 0000000..ecc9ce3 --- /dev/null +++ b/src/platform/API/Messaging/IEmailAccount.cpp @@ -0,0 +1,64 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IEmailAccount.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include +#include "IEmailAccount.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +IEmailAccount::IEmailAccount() : + m_validAccount(false) +{ +} + +IEmailAccount::~IEmailAccount() +{ +} + +void IEmailAccount::setCurrentEmailAccount(const EmailAccountInfo& account) +{ + m_currentAccount = account; +} + +EmailAccountInfo IEmailAccount::getCurrentEmailAccount() const +{ + return m_currentAccount; +} + +bool IEmailAccount::isCurrentAccountValid() const +{ + return m_validAccount; +} + +void IEmailAccount::setCurrentAccountValid(bool state) +{ + m_validAccount = state; +} +} +} +} diff --git a/src/platform/API/Messaging/IEmailAccount.h b/src/platform/API/Messaging/IEmailAccount.h new file mode 100755 index 0000000..b9a5fdf --- /dev/null +++ b/src/platform/API/Messaging/IEmailAccount.h @@ -0,0 +1,80 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file EmailAccount.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef IEMAILACCOUNT_H +#define IEMAILACCOUNT_H + +#include +#include "EmailAccountInfo.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class IEmailAccount +{ + public: + IEmailAccount(); + + virtual ~IEmailAccount(); + + /** + * setter of current email account value + */ + void setCurrentEmailAccount(const EmailAccountInfo& value); + + /** + * getter of current email account value + */ + EmailAccountInfo getCurrentEmailAccount() const; + + /** + * check validity state + */ + bool isCurrentAccountValid() const; + + /** + * setter for validity state + */ + void setCurrentAccountValid(bool state); + + private: + + /** + * abstract value of current email account + */ + EmailAccountInfo m_currentAccount; + + + /** + * information if abstract message current account has been changed + * and need update in low level + */ + bool m_validAccount; +}; +} +} +} +#endif // IEMAILACCOUNT_H diff --git a/src/platform/API/Messaging/IMessage.cpp b/src/platform/API/Messaging/IMessage.cpp new file mode 100755 index 0000000..cdfda72 --- /dev/null +++ b/src/platform/API/Messaging/IMessage.cpp @@ -0,0 +1,295 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IMessage.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include +#include +#include "IMessage.h" +#include "EventSendMessage.h" +#include "EventMessagingService.h" + +using namespace std; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +IMessage::IMessage(const MessageType msgType, + const string& id) : + m_id(id), + m_msgType(msgType), + m_readStatus(false), + m_validReadStatus(false), + m_isReadChangeStatus(false), + m_validisReadChangeStatus(true), + m_folder(DRAFTBOX), + m_requestReceiver(NULL), + m_sendMessageEvent(NULL) +{ + LogDebug("message creation, msgId=" << m_id << ", msgType=" << m_msgType); + + //initialize dateTime of message + time_t rawtime; + time(&rawtime); + tm* local = localtime(&rawtime); + if (local) { + m_dateTime = *local; + } else { + LogError("Failed to initialize message dateTime"); + } +} + +IMessage::~IMessage() +{ + LogDebug("destroying message, msgId=" << m_id << ", msgType=" << m_msgType); +} + +string IMessage::getId() const +{ + return m_id; +} + +const string& IMessage::getIdRef() const +{ + return m_id; +} + +MessageType IMessage::getMessageType() const +{ + return m_msgType; +} + +struct tm IMessage::getDateTime() const +{ + return m_dateTime; +} + +string IMessage::convertId(int arg) const +{ + ostringstream stream; + stream << arg; + return stream.str(); +} + +int IMessage::convertId(const string& arg) const +{ + int retVal = 0; + istringstream(arg) >> retVal; + return retVal; +} + +void IMessage::setId(const string& value) +{ + m_id = value; +} + +void IMessage::setDateTime(const tm dateTime) +{ + m_dateTime = dateTime; +} + +void IMessage::setReadStatus(bool state) +{ + m_validReadStatus = false; + m_readStatus = state; +} + +void IMessage::setSize(int size) +{ + m_size = size; +} + +int IMessage::getSize() const +{ + return m_size; +} + +bool IMessage::isRead() const +{ + return m_readStatus; +} + +bool IMessage::isReadStatusValid() const +{ + return m_validReadStatus; +} + +void IMessage::setReadStatusValidity(bool valid) +{ + m_validReadStatus = valid; +} + +bool IMessage::isReadChangeStatus() const +{ + return m_isReadChangeStatus; +} + +void IMessage::setisReadChangeStatus(bool state) +{ + m_validisReadChangeStatus = false; + m_isReadChangeStatus = state; +} + +bool IMessage::isReadChangeStatusValid() const +{ + return m_validisReadChangeStatus; +} + +void IMessage::setisReadChangeStatusValidity(bool valid) +{ + m_validisReadChangeStatus = valid; +} + +FolderType IMessage::getCurrentFolder() const +{ + return m_folder; +} + +void IMessage::setFolderType(FolderType folder) +{ + m_folder = folder; +} + +string IMessage::getCurrentUserFolder() const +{ + if (m_folder != USERDEFINED_FOLDER) { + LogError("folder is not user folder type"); + Throw(WrtDeviceApis::Commons::UnknownException); + } + return m_userFolderName; +} + +void IMessage::setCurrentUserFolder(const std::string& arg) +{ + m_userFolderName = arg; +} + +bool IMessage::validatePhoneNumber(std::string& number) +{ + LogDebug("testing number=" << number); + pcrecpp::RE re("[^0-9#\\+\\*]?"); + re.GlobalReplace("", &number); //remove invailde phone number. phone Number were composed only number. + + if (number.empty()) { + LogError("wrong phoneNumber=" << number); + return false; + } + LogDebug("phoneNumber=" << number); + + pcrecpp::RE re2("^[+#]?[0-9]{4,22}$"); + if (re2.FullMatch(number)) { + LogDebug("vaildate Number=" << number); + return true; + } + else + { + LogDebug("invaildate Number=" << number); + return false; + } + +} + +bool IMessage::validateEmailAddr(const Recipients& addr) +{ + for (size_t i = 0; i < addr.getRecipientSize(); i++) { + if (false == validateEmailAddr(addr.getRecipient(i))) { + LogError("wrong email address"); + return false; + } + } + return true; +} + +bool IMessage::validateEmailAddr(const std::string& email) +{ + if (email.empty()) { + return false; + } + pcrecpp::RE re( + "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}" + "\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\" + ".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$" + ); + if (re.FullMatch(email)) { + LogDebug("emailAddress=" << email); + return true; + } + LogError("wrong emailAddress=" << email); + return false; +} + +void IMessage::setEmitter(const EventOnSendingFailedEmitterPtr& emitter) +{ + m_emitter = emitter; +} + +EventOnSendingFailedEmitterPtr IMessage::getEmitter() const +{ + return m_emitter; +} + +void IMessage::setSendMessageEvent(const EventSendMessagePtr &event) +{ + m_sendMessageEvent = event; +} + +EventSendMessagePtr IMessage::getSendMessageEvent() const +{ + return m_sendMessageEvent; +} + +void IMessage::setMessagingServiceEvent(const EventMessagingServicePtr & event) +{ + m_messagingServiceEvent = event; +} + +EventMessagingServicePtr IMessage::getMessagingServiceEvent() const +{ + return m_messagingServiceEvent; +} + +void IMessage::setRequestReceiver(ReqReceiverMessage* reqReceiver) +{ + m_requestReceiver = reqReceiver; +} + +ReqReceiverMessage* IMessage::getRequestReceiver() const +{ + return m_requestReceiver; +} + +void IMessage::setMessageStatus( MessageStatus status) +{ + m_msgStatus = status; +} + +MessageStatus IMessage::getMessageStatus() const +{ + return m_msgStatus; +} + +} +} +} diff --git a/src/platform/API/Messaging/IMessage.h b/src/platform/API/Messaging/IMessage.h new file mode 100755 index 0000000..a111c9a --- /dev/null +++ b/src/platform/API/Messaging/IMessage.h @@ -0,0 +1,376 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IMessage.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef IMESSAGE_H +#define IMESSAGE_H + +#include +#include +#include +#include +#include "IMessagingTypes.h" +#include "ToRecipient.h" +#include "Body.h" +#include "From.h" +#include "SourceAddress.h" +#include "MessagePriority.h" +#include "CallbackNumber.h" +#include "ValidityPeriodHours.h" +#include "Subject.h" +#include "EventOnSendingFailed.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class EventSendMessage; +class EventMessagingService; +typedef DPL::SharedPtr EventSendMessagePtr; +typedef DPL::SharedPtr EventMessagingServicePtr; + +//-------------------------------------------------------------------------- + +class IMessage; +typedef DPL::SharedPtr IMessagePtr; + +//-------------------------------------------------------------------------- + +class ReqReceiverMessage; + +//-------------------------------------------------------------------------- + +class IMessage : + public DPL::EnableSharedFromThis, + public ToRecipient, + public Body, + public From, + public SourceAddress, + public MessagePriority, + public CallbackNumber, + public ValidityPeriodHours, + public Subject +{ + private: // fields + + /** + * id of message + */ + std::string m_id; + + /** + * message type value + */ + const MessageType m_msgType; + + /** + * message status value + */ + MessageStatus m_msgStatus; + + /** + * Message creation date time + */ + struct tm m_dateTime; + + /** + * Message read status + */ + bool m_readStatus; + + /** + * Read status validity. + */ + bool m_validReadStatus; + + /** + * Message IsRead Change status + */ + bool m_isReadChangeStatus; + + /** + * Change IsRead Change status validity. + */ + bool m_validisReadChangeStatus; + + /** + * Message size in bytes + */ + int m_size; + + /** + * Message current folder + */ + FolderType m_folder; + + /** + * User folder name + */ + std::string m_userFolderName; + + /* + * Event emitter. Used when there is one global callback function + */ + EventOnSendingFailedEmitterPtr m_emitter; + + /* + * Request receiver. Used when there are callback funtions assigned at function executing scope + */ + ReqReceiverMessage *m_requestReceiver; + + /* + * SendMessage event. Used when there are callback funtions assigned at function executing scope + */ + EventSendMessagePtr m_sendMessageEvent; + + /* + * Messaging Service event. Used when there are callback funtions assigned at function executing scope + */ + EventMessagingServicePtr m_messagingServiceEvent; + + protected: + void setSize(int size); + + public: // methods + + /** + * constructor of abstraction message + * @param[in] msgType - type of message according to MessageType + * @param[in] id - id of message, if id is empty, new message will be + * created, othercase message will be read from low + * level message + */ + explicit IMessage(const MessageType msgType, + const std::string& id = ""); + + virtual ~IMessage(); + + /** + * method is used to send message specyfied type + * @throw PlatformException Thrown when sending fail + */ + virtual int send() = 0; + + /** + * method is used to cancel sending message + * @throw PlatformException Thrown when sending fail + */ + virtual void sendCancel(int handle) = 0; + + /** + * method used to update all fields in lower level + * @param[in] draftsOnly - if true only draft messages can be + * fully updated. Other messages can only have read flag changed + * @throw PlatformException Thrown when update fail + */ + virtual void update(bool draftsOnly = false) = 0; + + + /** + * method used to updateIsRead + * @throw PlatformException Thrown when updateIsRead fail + */ + virtual void updateIsRead() = 0; + + + /** + * method used to read all data from low level message + * @throw PlatformException Thrown when reading message fail + */ + virtual void readAllData() = 0; + + /** + * method used to get current storage folder + */ + virtual FolderType getCurrentFolder() const; + + /** + * method used to get current user folder name + */ + virtual std::string getCurrentUserFolder() const; + + /** + * method used to set current user folder name + */ + void setCurrentUserFolder(const std::string& arg); + + /** + * method used to move message to new folder + * @param[in] newFolder - destination folder + * @throw PlatformException Thrown when move message to folder fail + */ + virtual void moveToFolder(const FolderType newFolder) = 0; + + /** + * method used to move message to user defined new folder + * @param[in] newFolder - users destination folder + * @throw PlatformException Thrown when move message to folder fail + */ + virtual void moveToFolder(const std::string& newFolder) = 0; + + /** + * method used to copy message to new folder (create new message with + * new message id) + * @param[in] newFolder - destination folder + * @throw PlatformException Thrown when copy message to folder fail + */ + virtual void copyToFolder(const FolderType newFolder) = 0; + + /** + * method used to copy message to user defined new folder + * @param[in] newFolder - users destination folder + * @throw PlatformException Thrown when move message to folder fail + */ + virtual void copyToFolder(const std::string& newFolder) = 0; + + /** + * method used to identify message type + */ + MessageType getMessageType() const; + + /** + * method used to get message id + */ + std::string getId() const; + + /** + * method used to get message size + */ + int getSize() const; + + /** + * method used to get message id + */ + virtual const std::string& getIdRef() const; + + /** + * used for get tm struct + */ + struct tm getDateTime() const; + + /** + * Is message already been read + */ + virtual bool isRead() const; + + /** + * Is message already been read + */ + virtual void setReadStatus(bool state); + + /** + * Returns true if read status is valid + */ + bool isReadStatusValid() const; + + /** + * Sets read status validity + */ + void setReadStatusValidity(bool valid); + + bool isReadChangeStatus() const; + + void setisReadChangeStatus(bool state); + + bool isReadChangeStatusValid() const; + + void setisReadChangeStatusValidity(bool valid); + + void setMessageStatus( MessageStatus status); + + MessageStatus getMessageStatus() const; + + /** + * Remove message + * @throw PlatformException Thrown when remove message fail + */ + virtual void remove() = 0; + + /** + * convert id from int to string + */ + virtual std::string convertId(int arg) const; + + /** + * convert id from string to int + */ + virtual int convertId(const std::string& arg) const; + + /** + * set message id + */ + void setId(const std::string& id); + + /** + * set date time + */ + void setDateTime(const tm dateTime); + + /** + * set current folder + */ + virtual void setFolderType(FolderType folder); + + /** + * validate phone number, if fail return false + * if number contains wrong characters, then cut them + */ + bool validatePhoneNumber(std::string& number); + + /** + * validate email address, if fail return false + */ + bool validateEmailAddr(const Recipients& addr); + + /** + * validate email address, if fail return false + */ + bool validateEmailAddr(const std::string& email); + + /* + * Sets event emitter + */ + void setEmitter(const EventOnSendingFailedEmitterPtr& emitter); + + /* + * Gets event emitter + */ + EventOnSendingFailedEmitterPtr getEmitter() const; + + void setSendMessageEvent(const EventSendMessagePtr &event); + + EventSendMessagePtr getSendMessageEvent() const; + + void setMessagingServiceEvent(const EventMessagingServicePtr &event); + + EventMessagingServicePtr getMessagingServiceEvent() const; + + void setRequestReceiver(ReqReceiverMessage* reqReceiver); + + ReqReceiverMessage* getRequestReceiver() const; +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/IMessageFolder.h b/src/platform/API/Messaging/IMessageFolder.h new file mode 100755 index 0000000..f86731e --- /dev/null +++ b/src/platform/API/Messaging/IMessageFolder.h @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** +* @file IMessageFolder.h +* @author Oy Kwon (sirot.kwon@samsung.com) +* @version 0.1 +*/ + +#ifndef IMESSAGEFOLDER_H +#define IMESSAGEFOLDER_H + +#include +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class IMessageFolder; +typedef DPL::SharedPtr IMessageFolderPtr; + +class IMessageFolder +{ +public: + + IMessageFolder() {} + virtual ~IMessageFolder() {}; + + virtual void setName(std::string name)=0; + virtual void setSynchronizable(bool synchronizable)=0; + + virtual unsigned long getId()=0; + virtual unsigned long getParentId()=0; + virtual unsigned long getAccountId()=0; + virtual unsigned short getContentType()=0; + virtual std::string getName()=0; + virtual std::string getPath()=0; + virtual unsigned short getType()=0; + virtual bool getSynchronizable()=0; +}; +} +} +} + +#endif + diff --git a/src/platform/API/Messaging/IMessaging.cpp b/src/platform/API/Messaging/IMessaging.cpp new file mode 100755 index 0000000..9513594 --- /dev/null +++ b/src/platform/API/Messaging/IMessaging.cpp @@ -0,0 +1,45 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IMessaging.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "IMessaging.h" +#include + +using namespace TizenApis::Platform::Messaging; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +IMessaging& IMessaging::getInstance() +{ + return TizenApis::Platform::Messaging::Messaging::getInstance(); +} + +IMessaging::~IMessaging() +{ +} +} +} +} diff --git a/src/platform/API/Messaging/IMessaging.h b/src/platform/API/Messaging/IMessaging.h new file mode 100755 index 0000000..0df17ed --- /dev/null +++ b/src/platform/API/Messaging/IMessaging.h @@ -0,0 +1,117 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IMessaging.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef IMESSAGING_H +#define IMESSAGING_H + +#include +#include "IMessagingTypes.h" +#include "ISms.h" +#include "IBinarySms.h" +#include "IMms.h" +#include "IEmail.h" +#include "VirtualMessage.h" +#include "MessageFactory.h" +#include "IEmailAccount.h" +#include "EmitterMessageReceived.h" +#include "EmitterConversationReceived.h" +#include "EmitterFolderReceived.h" +#include "IConversation.h" +#include "IMessageFolder.h" +#include +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class IMessaging : private DPL::Noncopyable, + public IEmailAccount +{ + public: + static IMessaging& getInstance(); + + public: + virtual ~IMessaging() = 0; + + virtual void getNumberOfMessages(MessageType msgType, + FolderType folder, + int* readed, + int* unReaded) = 0; + + virtual std::vector findMessages( + const std::vector& msgTypes, + FolderType folder, +// const Api::Messaging::MessageFilterPtr& filter) = 0; + const Api::Tizen::FilterPtr& filter) = 0; + + virtual std::vector findMessages( + const std::vector& msgTypes, + const std::string &folder, +// const Api::Messaging::MessageFilterPtr& filter) = 0; + const Api::Tizen::FilterPtr& filter) = 0; + + virtual std::vector findMessages(const Api::Tizen::FilterPtr& filter, + const Api::Tizen::SortModePtr& sortMode, const long limit, const long offset) = 0; + virtual std::vector findMessages(const Api::Tizen::FilterPtr& filter) = 0; + + virtual std::vector getMessageIds(MessageType msgType, + FolderType folder) = 0; + + virtual void createFolder(MessageType msgType, + const std::string& userFolder) = 0; + + virtual void deleteFolder(MessageType msgType, + const std::string& userFolder) = 0; + + virtual std::vector getFolderNames(MessageType msgType) = 0; + + virtual void addOnMessageReceived(const EmitterMessageReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, const int funtionIndex) + = 0; + virtual void addOnMessageReceived(const EmitterConversationReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, const int funtionIndex) + = 0; + virtual void addOnMessageReceived(const EmitterFolderReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, const int funtionIndex) + = 0; + + virtual void removeOnMessageMsgReceived(EmitterMessageReceived::IdType id) = 0; + + virtual void removeOnMessageConvReceived(EmitterConversationReceived::IdType id) = 0; + + virtual void removeOnMessageFolderReceived(EmitterFolderReceived::IdType id) = 0; + + virtual int getConversationId(const int& msgId, const MessageType &msgtype) = 0; + + virtual std::vector queryConversations(const Api::Tizen::SortModePtr& sortMode, const Api::Tizen::FilterPtr& filter, long limit=0, long offset=0) = 0; + virtual bool deleteConversations(const Api::Tizen::SortModePtr& sortMode, const Api::Tizen::FilterPtr& filter) = 0; + virtual bool deleteConversations(const std::vector& conversations) = 0; + virtual std::vector queryFolders(const Api::Tizen::FilterPtr& filter) = 0; + + + virtual void fetchEmailHeaders() = 0; +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/IMessagingService.cpp b/src/platform/API/Messaging/IMessagingService.cpp new file mode 100755 index 0000000..4a604e3 --- /dev/null +++ b/src/platform/API/Messaging/IMessagingService.cpp @@ -0,0 +1,60 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author + */ + +#include "IMessagingService.h" +#include "EventGetMessagingService.h" +#include "EventMessagingService.h" + +using namespace TizenApis::Api::Messaging; +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { +namespace Api { +namespace Messaging{ + +IMessagingService::IMessagingService() : + m_messagingServiceType(-1) +{ + LogDebug("create IMessagingService"); +} + +IMessagingService::~IMessagingService() +{ + LogDebug("destory IMessagingService"); +} + +void IMessagingService::setMessagingServiceEvent(const EventMessagingServicePtr &event) +{ + m_messagingServiceEvent = event; +} + +EventMessagingServicePtr IMessagingService::getMessagingServiceEvent() const +{ + return m_messagingServiceEvent; +} + + +} +} +} + + + diff --git a/src/platform/API/Messaging/IMessagingService.h b/src/platform/API/Messaging/IMessagingService.h new file mode 100755 index 0000000..9674ed5 --- /dev/null +++ b/src/platform/API/Messaging/IMessagingService.h @@ -0,0 +1,155 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author Dongjin, Choi + */ + +#ifndef WRTPLUGINS_API_IMESSAGING_SERVICE_H_ +#define WRTPLUGINS_API_IMESSAGING_SERVICE_H_ + +#include +#include "IMessagingTypes.h" +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +enum MessagingServiceOpType +{ + MESSAGING_SERVICE_OP_SEND_MESSAGE = 0, + MESSAGING_SERVICE_OP_DOWNLOAD_BODY, + MESSAGING_SERVICE_OP_DOWNLOAD_ATTACHMENT, + MESSAGING_SERVICE_OP_SYNC, + MESSAGING_SERVICE_OP_SYNC_FOLDER, + MESSAGING_SERVICE_OP_COUNT, +}; + +class ReqReceiverMessage; +class IMessagingService; + +typedef DPL::SharedPtr IMessagingServicePtr; + +class IMessagingService: + public IEmailAccount +{ +public: + virtual ~IMessagingService(); + +// /** +// * Gets a service of messaging +// * @param event @see TizenApis::Api::PluginTemplete::EventGetMessagingService +// * @exception WrtDeviceApis::Commons::PlatformException when platform error occurs +// */ + + int getAccountID() const + { + if ( m_messagingServiceType == Api::Messaging::EMAIL) + { + return getCurrentEmailAccount().getIntId(); + } + else + { + return -1; //default is -1 + } + } + + int getType() const + { + return m_messagingServiceType; + } + + std::string getName() const + { + if ( m_messagingServiceType == Api::Messaging::EMAIL) + { + return getCurrentEmailAccount().getName(); + } + else + { + return m_messagingServiceName; + } + } + + virtual int createOpId(int type) = 0; + virtual int getHandleFromOpId(int opId) = 0; + virtual int getOpTypeFromOpId(int opId) = 0; + virtual Api::Messaging::IMessagePtr getMessageFromOpId(int opId) = 0; + virtual void setHandleToOpId(int opId, int handle) = 0; + virtual void setMessageToOpId(int opId, Api::Messaging::IMessagePtr& message) = 0; + virtual int deleteOpId(int opId)=0; + + virtual int sync(const Api::Messaging::IMessagingServicePtr& messagingService, const int limit) = 0; + virtual void syncCancel(int handle) = 0; + virtual int syncFolder(const Api::Messaging::IMessagingServicePtr& messagingService, const std::string& folder_name, const int limit) = 0; + virtual void syncFolderCancel(int handle) = 0; + + void setMessagingServiceEvent(const EventMessagingServicePtr &event); + EventMessagingServicePtr getMessagingServiceEvent() const; + + void setRequestReceiver(ReqReceiverMessage* reqReceiver) + { + m_requestReceiver = reqReceiver; + } + + ReqReceiverMessage* getRequestReceiver() const + { + return m_requestReceiver; + } + +private: + short m_messagingServiceType; //type + std::string m_messagingServiceName; + /* + * Request receiver. Used when there are callback funtions assigned at function executing scope + */ + ReqReceiverMessage *m_requestReceiver; + + /* + * Messaging Service event. Used when there are callback funtions assigned at function executing scope + */ + EventMessagingServicePtr m_messagingServiceEvent; + +protected: + IMessagingService(); + + void setType(int type) + { + m_messagingServiceType = type; + } + + void setName(const std::string& name = "" ) + { + m_messagingServiceName = name; + } + +}; + +} +} +} + +#endif //WRTPLUGINS_API_IMESSAGING_SERVICE_H_ + + + diff --git a/src/platform/API/Messaging/IMessagingServiceManager.cpp b/src/platform/API/Messaging/IMessagingServiceManager.cpp new file mode 100755 index 0000000..3a9061d --- /dev/null +++ b/src/platform/API/Messaging/IMessagingServiceManager.cpp @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author + */ + +#include "IMessagingServiceManager.h" + +using namespace TizenApis::Api::Messaging; +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { +namespace Api { +namespace Messaging{ + +IMessagingServiceManager::IMessagingServiceManager() : + EventRequestReceiver(ThreadEnum::MESSAGING_THREAD) +{ +} + +IMessagingServiceManager::~IMessagingServiceManager() +{ +} + +} +} +} diff --git a/src/platform/API/Messaging/IMessagingServiceManager.h b/src/platform/API/Messaging/IMessagingServiceManager.h new file mode 100755 index 0000000..ff84e8b --- /dev/null +++ b/src/platform/API/Messaging/IMessagingServiceManager.h @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author Dongjin, Choi + */ + +#ifndef WRTPLUGINS_API_IMESSAGING_SERVICE_MANAGER_H_ +#define WRTPLUGINS_API_IMESSAGING_SERVICE_MANAGER_H_ + +#include +#include + +#include "IMessagingTypes.h" +#include +#include + +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//class EventGetMessagingService; +//typedef DPL::SharedPtr EventGetMessagingServicePtr; + +class IMessagingServiceManager: + public WrtDeviceApis::Commons::EventRequestReceiver +{ +public: + virtual ~IMessagingServiceManager(); + +// /** +// * Gets a service of messaging +// * @param event @see TizenApis::Api::PluginTemplete::EventGetMessagingService +// * @exception WrtDeviceApis::Commons::PlatformException when platform error occurs +// */ + virtual void getMessagingServiceManager (const EventGetMessagingServicePtr& event) = 0; + +protected: + std::vector< IMessagingServicePtr > m_messagingServices; //service list vector. + IMessagingServiceManager(); + + virtual void OnRequestReceived(const EventGetMessagingServicePtr& event) = 0; +}; + +typedef DPL::SharedPtr IMessagingServiceManagerPtr; + +} +} +} + +#endif /* WRTPLUGINS_API_IMESSAGING_SERVICE_MANAGER_H_ */ diff --git a/src/platform/API/Messaging/IMessagingTypes.h b/src/platform/API/Messaging/IMessagingTypes.h new file mode 100755 index 0000000..377f0b3 --- /dev/null +++ b/src/platform/API/Messaging/IMessagingTypes.h @@ -0,0 +1,86 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IMessagingTypes.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef IMESSAGINGTYPES_H +#define IMESSAGINGTYPES_H + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +#define NAME_SMS_TYPE "SMS" +#define NAME_MMS_TYPE "MMS" +#define NAME_EMAIL_TYPE "EMAIL" +#define NAME_CHAT_TYPE "CHAT" + +enum MessageType +{ + SMS = 1, + MMS, + EMAIL, + CHAT, + BINARYSMS, + VIRTUAL_MESSAGE, + MESSAGETYPE_COUNT +}; + +enum MessageStatus +{ + MESSAGE_STATUS_SENT = 1, + MESSAGE_STATUS_SENDING , + MESSAGE_STATUS_FAILED, + MESSAGE_STATUS_DRAFT, +}; + +//-------------------------------------------------------------------------- + +enum FolderType +{ + INBOX = 1, + OUTBOX = 2, + DRAFTBOX = 3, + SENTBOX =4, + SPAMBOX, + ALL_FOLDERS, + USERDEFINED_FOLDER, + FOLDERTYPE_COUNT +}; + +//-------------------------------------------------------------------------- + +enum AddressType +{ + TO_ADDRESS, + CC_ADDRESS, + BCC_ADDRESS, + ADDRESS_COUNT +}; +} +} +} +#endif + diff --git a/src/platform/API/Messaging/IMms.cpp b/src/platform/API/Messaging/IMms.cpp new file mode 100755 index 0000000..c69067c --- /dev/null +++ b/src/platform/API/Messaging/IMms.cpp @@ -0,0 +1,80 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IMms.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "IMms.h" +#include "ValidityPeriodHours.h" +#include + +using namespace std; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +IMms::IMms(const string& id) : + IMessage(MMS, id), + m_mmsType(MULTIPART_MIXED) +{ + LogInfo("enter"); +} + +IMms::~IMms() +{ + LogInfo("enter"); +} + +IMms::MMSType IMms::getMmsType() const +{ + return m_mmsType; +} + +void IMms::setMmsType(MMSType type) +{ + m_mmsType = type; +} + +IMms & IMms::operator <<(const VirtualMessage& msg) +{ + setBody(msg.getBodyRef()); + setFolderType(msg.getCurrentFolder()); + setCurrentUserFolder(msg.getCurrentUserFolder()); + setFrom(msg.getFromRef()); + setDateTime(msg.getDateTime()); + setSourceAddress(msg.getSourceAddress()); + setToRecipients(msg.getToRecipients()); + setValidityPeriodHours(msg.getValidityPeriodHours()); + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + setAttachments(msg.getAttachments()); +#endif + setBccRecipients(msg.getBccRecipients()); + setCcRecipients(msg.getCcRecipients()); + setSubject(msg.getSubjectRef()); + + return *this; +} +} +} +} diff --git a/src/platform/API/Messaging/IMms.h b/src/platform/API/Messaging/IMms.h new file mode 100755 index 0000000..9726f51 --- /dev/null +++ b/src/platform/API/Messaging/IMms.h @@ -0,0 +1,91 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IMms.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef IMMS_H +#define IMMS_H + +#include +#include +#include "VirtualMessage.h" +#include "IMessage.h" +#include "Subject.h" +#include "ToRecipient.h" +#include "CcRecipient.h" +#include "BccRecipient.h" +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +#include "Attachments.h" +#endif +#include "IMmsSlides.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class IMms; +typedef DPL::SharedPtr IMmsPtr; + +class IMms : + virtual public IMessage, + virtual public IMmsSlides, + public CcRecipient, + public BccRecipient +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + , + public Attachments +#endif +{ + public: // fields + + enum MMSType + { + MULTIPART_MIXED = 0, + MULTIPART_RELATED = 1 + }; + + public: // methods + + explicit IMms(const std::string& id = ""); + + virtual ~IMms(); + + /** + * geter for mms type + * */ + virtual MMSType getMmsType() const; + + /** + * seter for mms type + * */ + virtual void setMmsType(MMSType type); + + IMms & operator <<(const VirtualMessage& msg); + + private: + MMSType m_mmsType; +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/IMmsSlide.h b/src/platform/API/Messaging/IMmsSlide.h new file mode 100755 index 0000000..97e4455 --- /dev/null +++ b/src/platform/API/Messaging/IMmsSlide.h @@ -0,0 +1,69 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IMmsSlide.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef IMMSSLIDE_H +#define IMMSSLIDE_H + +#include + +#include "IMmsSlideProperties.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class IMmsSlide; +typedef DPL::SharedPtr IMmsSlidePtr; + +class IMmsSlide : + public IMmsSlidePropertyImage, + public IMmsSlidePropertyAudio, + public IMmsSlidePropertyText, + public IMmsSlidePropertyVideo +{ + public: + typedef unsigned long Ulong; + + public: // methods + + virtual ~IMmsSlide() + { + } + + /** + * Get duration + */ + virtual Ulong getDuration() const = 0; + + /** + * Set duration + * @param[in] - value in miliseconds + */ + virtual void setDuration(Ulong duration) = 0; +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/IMmsSlideProperties.h b/src/platform/API/Messaging/IMmsSlideProperties.h new file mode 100755 index 0000000..b8c59cd --- /dev/null +++ b/src/platform/API/Messaging/IMmsSlideProperties.h @@ -0,0 +1,247 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * @file IMmsSlideProperties.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef IMMS_SLIDE_PROPERTIES_H +#define IMMS_SLIDE_PROPERTIES_H + +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class IMmsSlidePropertyImage +{ + public: + typedef unsigned long Ulong; + + public: + + virtual ~IMmsSlidePropertyImage() + { + } + + /** + * get image filename + * */ + virtual const std::string& getImageFilename() const = 0; + + /** + * get image filename + * @param[in] picture filename + * @throw MMS_MESSAGE_SIZE_EXCEEDED_ERROR + * @throw MMS_VIDEO_SLIDE_ERROR + * */ + virtual void setImageFilename(const std::string& filename) = 0; + + /** + * get imageBegin + * begining of image presentation within a slide in milisecond + * */ + virtual Ulong getImageBegin() const = 0; + + /** + * set imageBegin; + * begining of image presentation within a slide in milisecond + * @param[in] - value in miliseconds + * */ + virtual void setImageBegin(Ulong value) = 0; + + /** + * get imageEnd + * end of image presentation within a slide in milisecond + * */ + virtual Ulong getImageEnd() const = 0; + + /** + * set imageBegin; + * end of image presentation within a slide in milisecond + * @param[in] - value in miliseconds + * */ + virtual void setImageEnd(Ulong value) = 0; +}; + +//-------------------------------------------------------------------------- + +class IMmsSlidePropertyAudio +{ + public: + typedef unsigned long Ulong; + + public: + + virtual ~IMmsSlidePropertyAudio() + { + } + + /** + * get audio filename + * */ + virtual const std::string& getAudioFilename() const = 0; + + /** + * get audio filename + * @param[in] audio filename + * @throw MMS_MESSAGE_SIZE_EXCEEDED_ERROR + * @throw MMS_VIDEO_SLIDE_ERROR + * */ + virtual void setAudioFilename(const std::string& filename) = 0; + + /** + * get audio begin + * begining of image presentation within a slide in milisecond + * */ + virtual Ulong getAudioBegin() const = 0; + + /** + * set audio begin; + * begining of audio presentation within a slide in milisecond + * @param[in] - value in miliseconds + * */ + virtual void setAudioBegin(Ulong value) = 0; + + /** + * get audioEnd + * end of audio presentation within a slide in milisecond + * */ + virtual Ulong getAudioEnd() const = 0; + + /** + * set audioEnd; + * end of audio presentation within a slide in milisecond + * @param[in] - value in miliseconds + * */ + virtual void setAudioEnd(Ulong value) = 0; +}; + +//-------------------------------------------------------------------------- + +class IMmsSlidePropertyText +{ + public: + typedef unsigned long Ulong; + + public: + + virtual ~IMmsSlidePropertyText() + { + } + + /** + * get text filename + * */ + virtual const std::string& getTextFilename() const = 0; + + /** + * get text filename + * @param[in] text filename + * @throw MMS_MESSAGE_SIZE_EXCEEDED_ERROR + * @throw MMS_VIDEO_SLIDE_ERROR + * */ + virtual void setTextFilename(const std::string& filename) = 0; + + /** + * get text begin + * begining of text presentation within a slide in milisecond + * */ + virtual Ulong getTextBegin() const = 0; + + /** + * set text begin; + * begining of text presentation within a slide in milisecond + * @param[in] - value in miliseconds + * */ + virtual void setTextBegin(Ulong value) = 0; + + /** + * get textEnd + * end of text presentation within a slide in milisecond + * */ + virtual Ulong getTextEnd() const = 0; + + /** + * set textEnd; + * end of text presentation within a slide in milisecond + * @param[in] - value in miliseconds + * */ + virtual void setTextEnd(Ulong value) = 0; +}; + +//-------------------------------------------------------------------------- + +class IMmsSlidePropertyVideo +{ + public: + typedef unsigned long Ulong; + + public: + + virtual ~IMmsSlidePropertyVideo() + { + } + + /** + * get video filename + * */ + virtual const std::string& getVideoFilename() const = 0; + + /** + * get video filename + * @param[in] vdeo filename + * @throw MMS_MESSAGE_SIZE_EXCEEDED_ERROR + * @throw MMS_VIDEO_SLIDE_ERROR + * */ + virtual void setVideoFilename(const std::string& filename) = 0; + + /** + * get video begin + * begining of video presentation within a slide in milisecond + * */ + virtual Ulong getVideoBegin() const = 0; + + /** + * set video begin; + * begining of video presentation within a slide in milisecond + * @param[in] - value in miliseconds + * */ + virtual void setVideoBegin(Ulong value) = 0; + + /** + * get videoEnd + * end of video presentation within a slide in milisecond + * */ + virtual Ulong getVideoEnd() const = 0; + + /** + * set videoEnd; + * end of video presentation within a slide in milisecond + * @param[in] - value in miliseconds + * */ + virtual void setVideoEnd(Ulong value) = 0; +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/IMmsSlides.h b/src/platform/API/Messaging/IMmsSlides.h new file mode 100755 index 0000000..ce24c5c --- /dev/null +++ b/src/platform/API/Messaging/IMmsSlides.h @@ -0,0 +1,112 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file IMmsSlides.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef IMMS_SLIDES_H +#define IMMS_SLIDES_H + +#include + +#include "IMmsSlide.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class IMmsSlides +{ + public: + + virtual ~IMmsSlides() + { + } + + /** + * create empty slide + * @return shared pointer to created IMmsSlide + * */ + virtual IMmsSlidePtr createEmptySlide() const = 0; + + /** + * check data validity + * @return true if slides are valid + * or false if one or more slide need update + * */ + virtual bool checkSlidesValidity() const = 0; + + /** + * set data validity + * */ + virtual void setSlidesValidity(bool state) = 0; + + /** + * set slides + * */ + virtual void setSlides(const std::vector& slides) = 0; + + /** + * add slide to mms object + * */ + virtual void addSlide(const IMmsSlidePtr& slide) = 0; + + /** + * get slide count + * @return number of slides in mms + * */ + virtual size_t getSlideCount() const = 0; + + /** + * get slide by number + * @return shared pointer to IMmsSlide + * @throw INVALID_ARGUMENT_EXCEPTION + * if argument is wrong + * */ + virtual IMmsSlidePtr getSlide(size_t nb) const = 0; + + /** + * get slides + * @return vector of slides from Mms + * */ + virtual std::vector getSlides() const = 0; + + /** + * replace slide + * @throw INVALID_ARGUMENT_EXCEPTION + * if argument is wrong + * */ + virtual void replaceSlide(size_t pos, + const IMmsSlidePtr& slide) = 0; + + /** + * remove slide + * @throw INVALID_ARGUMENT_EXCEPTION + * if argument is wrong + * */ + virtual void removeSlide(size_t pos) = 0; +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/ISms.cpp b/src/platform/API/Messaging/ISms.cpp new file mode 100755 index 0000000..68eb6c8 --- /dev/null +++ b/src/platform/API/Messaging/ISms.cpp @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file ISms.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "ISms.h" +#include + +using namespace std; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +ISms::ISms(const string& id) : + IMessage(SMS, id) +{ + LogInfo("enter"); +} + +ISms::~ISms() +{ + LogInfo("enter"); +} + +ISms & ISms::operator <<(const VirtualMessage& msg) +{ + setBody(msg.getBodyRef()); + setFolderType(msg.getCurrentFolder()); + setCurrentUserFolder(msg.getCurrentUserFolder()); + setFrom(msg.getFromRef()); + setDateTime(msg.getDateTime()); + setSourceAddress(msg.getSourceAddress()); + setToRecipients(msg.getToRecipients()); + setCallbackNumber(getCallbackNumberRef()); + setValidityPeriodHours(msg.getValidityPeriodHours()); + + return *this; +} +} +} +} diff --git a/src/platform/API/Messaging/ISms.h b/src/platform/API/Messaging/ISms.h new file mode 100755 index 0000000..2d7e983 --- /dev/null +++ b/src/platform/API/Messaging/ISms.h @@ -0,0 +1,60 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file ISms.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef ISMS_H +#define ISMS_H + +#include "IMessage.h" +#include "CallbackNumber.h" +#include "VirtualMessage.h" +#include "ValidityPeriodHours.h" +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class ISms; +typedef DPL::SharedPtr ISmsPtr; + +class ISms : + virtual public IMessage +{ + public: // fields + + public: // methods + + explicit ISms(const std::string& id = ""); + + virtual ~ISms(); + + ISms & operator <<(const VirtualMessage& msg); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/MessageEventPrivateData.h b/src/platform/API/Messaging/MessageEventPrivateData.h new file mode 100755 index 0000000..f3e02f3 --- /dev/null +++ b/src/platform/API/Messaging/MessageEventPrivateData.h @@ -0,0 +1,63 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file MessageEventPrivateData.h + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef MESSAGEEVENTPRIVATEDATA_H_ +#define MESSAGEEVENTPRIVATEDATA_H_ + +#include +#include +#include "IMessage.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +/* + * I cannot put IMessagePtr directly in EventOnSendingFailed because the IMessage contains an emitter based on this event + * and I get recurring include dependency and I don't want to mix standard pointers with shared pointers. + */ +class MessageEventPrivateData : public WrtDeviceApis::Commons::IEventPrivateData +{ + public: + explicit MessageEventPrivateData(const IMessagePtr& message) : m_message( + message) + { + } + + IMessagePtr GetMessage() const + { + return m_message; + } + + private: + IMessagePtr m_message; +}; + +typedef DPL::SharedPtr MessageEventPrivateDataPtr; +} // Api +} // WrtPlugins +} +#endif /* MESSAGEEVENTPRIVATEDATA_H_ */ diff --git a/src/platform/API/Messaging/MessageFactory.cpp b/src/platform/API/Messaging/MessageFactory.cpp new file mode 100755 index 0000000..a40af85 --- /dev/null +++ b/src/platform/API/Messaging/MessageFactory.cpp @@ -0,0 +1,210 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file MessageFactory.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include +#include +#include +#include +#include +#include "MessageFactory.h" +#include + +using namespace std; +using namespace WrtDeviceApis::Commons; +using namespace TizenApis::Platform::Messaging; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +IMessagePtr MessageFactory::createMessage(const MessageType msgType, + const std::string& id) +{ + LogInfo("enter"); + IMessage* retVal = NULL; + switch (msgType) { + case SMS: + LogDebug("creation sms message"); + retVal = new Sms(id); + break; + + case BINARYSMS: + LogDebug("creation binary sms message"); + retVal = new BinarySms(id); + break; + + case MMS: + LogDebug("creation mms message"); + retVal = new Mms(id); + break; + + case EMAIL: + LogDebug("creation email message"); + retVal = new Email(id); + break; + + default: + LogError("creation error, unknown message type"); + break; + } + return IMessagePtr(retVal); +} + +IMessagePtr MessageFactory::createMessage(const MessageType msgType, + const int id) +{ + std::ostringstream stream; + stream << id; + std::string idStr = stream.str(); + return createMessage(msgType, idStr); +} + +IMessagePtr MessageFactory::createMessage(const MessageType msgType, + Api::Messaging::EmailAccountInfo& account, const std::string& id ) +{ + LogInfo("enter, CreateMessage with account"); + + std::ostringstream stream; + stream << id; + std::string idStr = stream.str(); + + LogInfo("createMessage with , idstr =" << idStr); + + if (msgType == EMAIL) + { + LogDebug("Account Address:" << &account); + IMessage* retVal = NULL; + LogDebug("creation email message with account"); + retVal = new Email(account); + return IMessagePtr(retVal); + } + + return createMessage(msgType, idStr); + +} + +IMessagePtr MessageFactory::createEmailMessage(const int mailId, const int accountId) +{ + LogInfo("enter, Create Email Message with account ID"); + IEmail* email = NULL; + LogDebug("creation email message with account ID"); + std::stringstream stream; + stream << mailId; + if (stream.fail()) { + ThrowMsg(UnknownException, "Couldn't convert e-mail account id"); + } + + email = new Email(stream.str(), accountId); + + IMessagePtr imsg(email); +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + std::vector attachments = email->getAttachments(); + + int idx = 0; + for (; idx < attachments.size() ; idx++ ) + { + LogDebug("set Messsage ID = " << attachments[idx]->getAttachmentID()); + attachments[idx]->setMessage(imsg); + } +#endif + + return imsg; + + +#if 0 + IMessage* retVal = NULL; + LogDebug("creation email message with account ID"); + + + std::stringstream stream; + stream << mailId; + if (stream.fail()) { + ThrowMsg(UnknownException, "Couldn't convert e-mail account id"); + } + + retVal = new Email(stream.str(), accountId); + + + + + + return IMessagePtr(retVal); +#endif +} + +IMessagePtr MessageFactory::createVirtualMessage() +{ + return IMessagePtr(new VirtualMessage()); +} + +VirtualMessagePtr MessageFactory::convertToVirtualMessage(IMessagePtr msg) +{ + VirtualMessagePtr tmp = DPL::DynamicPointerCast(msg); + if (!tmp) { + ThrowMsg(ConversionException, + "Conversion IMessage to VirtualMessagePtr error"); + } + return tmp; +} + +ISmsPtr MessageFactory::convertToSms(IMessagePtr msg) +{ + ISmsPtr tmp = DPL::DynamicPointerCast(msg); + if (!tmp) { + ThrowMsg(ConversionException, "Conversion IMessage to ISms error"); + } + return tmp; +} + +IBinarySmsPtr MessageFactory::convertToBinarySms(IMessagePtr msg) +{ + IBinarySmsPtr tmp = DPL::DynamicPointerCast(msg); + if (!tmp) { + ThrowMsg(ConversionException, "Conversion IMessage to IBinarySms error"); + } + return tmp; +} + +IMmsPtr MessageFactory::convertToMms(IMessagePtr msg) +{ + IMmsPtr tmp = DPL::DynamicPointerCast(msg); + if (!tmp) { + ThrowMsg(ConversionException, "Conversion IMessage to IMms error"); + } + return tmp; +} + +IEmailPtr MessageFactory::convertToEmail(IMessagePtr msg) +{ + IEmailPtr tmp = DPL::DynamicPointerCast(msg); + if (!tmp) { + ThrowMsg(ConversionException, "Conversion IMessage to IEmail error"); + } + return tmp; +} +} +} +} diff --git a/src/platform/API/Messaging/MessageFactory.h b/src/platform/API/Messaging/MessageFactory.h new file mode 100755 index 0000000..12a12fc --- /dev/null +++ b/src/platform/API/Messaging/MessageFactory.h @@ -0,0 +1,116 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file MessageFactory.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef MESSAGEFACTORY_H +#define MESSAGEFACTORY_H + +#include +#include "IMessaging.h" +#include "IMessage.h" +#include "EmailAccountInfo.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class MessageFactory +{ + public: + + /** + * Generate message specyfied type + * @param[in] msgType type of message to create + * @param[in] id if id is set, then is trying to read existing message + * from storage by specyfid if + */ + static IMessagePtr createMessage(const MessageType msgType, + const std::string& id = ""); + + /** + * Generate message specyfied type + * @param[in] msgType type of message to create + * @param[in] int id + * from storage by specyfid if + */ + static IMessagePtr createMessage(const MessageType msgType, + const int id); + + /** + * Generate message specyfied type + * @param[in] msgType type of message to create + * @param[in] account of mail. + */ + static IMessagePtr createMessage(const MessageType msgType, + Api::Messaging::EmailAccountInfo& account, const std::string& id = "" ); + + static IMessagePtr createEmailMessage ( const int id = 0, const int accountId = 0); + + /** + * Generate virtual message specyfied type, without platform projection + * @param[in] msgType type of message to create + */ + static IMessagePtr createVirtualMessage(); + + /** + * Convert abstract message (IMessage) to virtual message + * @param[in] msg - pointer to message to convert + * @throw ConversionException if conversion fail + */ + static VirtualMessagePtr convertToVirtualMessage(IMessagePtr msg); + + /** + * Convert abstract message (IMessage) to abstract sms (ISms) + * @param[in] msg - pointer to message to convert + * @throw ConversionException if conversion fail + */ + static ISmsPtr convertToSms(IMessagePtr msg); + + /** + * Convert abstract message (IMessage) to abstract binary sms (IBinarySms) + * @param[in] msg - pointer to message to convert + * @throw ConversionException if conversion fail + */ + static IBinarySmsPtr convertToBinarySms(IMessagePtr msg); + + /** + * Convert abstract message (IMessage) to abstract Mms (IMms) + * @param[in] msg - pointer to message to convert + * @throw ConversionException if conversion fail + */ + static IMmsPtr convertToMms(IMessagePtr msg); + + /** + * Convert abstract message (IMessage) to abstract email (IEmail) + * @param[in] msg - pointer to message to convert + * @throw ConversionException if conversion fail + */ + static IEmailPtr convertToEmail(IMessagePtr msg); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/MessageFilterValidator.cpp b/src/platform/API/Messaging/MessageFilterValidator.cpp new file mode 100755 index 0000000..fe851ba --- /dev/null +++ b/src/platform/API/Messaging/MessageFilterValidator.cpp @@ -0,0 +1,171 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * MessageFilterValidator.cpp + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#include "MessageFilterValidator.h" +#include "MessageFilterValidatorFactory.h" + +#include +#include "log.h" + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + MessageFilterValidator::MessageFilterValidator(PropertyStructArray properties, + MatchFlagStrArray matchFlag, Api::Tizen::PrimitiveType idType):FilterValidator(properties, matchFlag){ + m_isTypeSetted = false; + + initMatchFlagVectors(); + initAttributeAndMatchFlagsMap(); + } + + MessageFilterValidator::~MessageFilterValidator(){ + } + + void MessageFilterValidator::initMatchFlagVectors(){ + m_typeMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_EXACTLY); + + m_idMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_EXACTLY); + + m_folderIdMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_EXACTLY); + + m_timestampMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_EXACTLY); + + m_fromMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_EXACTLY); + m_fromMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_CONTAINS); + m_fromMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_STARTSWITH); + m_fromMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_ENDSWITH); + + m_toMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_EXACTLY); + m_toMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_CONTAINS); + m_toMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_STARTSWITH); + m_toMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_ENDSWITH); + + m_ccMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_EXACTLY); + m_ccMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_CONTAINS); + m_ccMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_STARTSWITH); + m_ccMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_ENDSWITH); + + m_bccMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_EXACTLY); + m_bccMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_CONTAINS); + m_bccMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_STARTSWITH); + m_bccMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_ENDSWITH); + + m_bodyMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_CONTAINS); + + m_isReadMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_EXACTLY); + + m_priorityMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_EXACTLY); + + m_subjectMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_EXACTLY); + m_subjectMatchFlagVec.push_back(MessageFilterValidatorFactory::MATCH_CONTAINS); + } + + void MessageFilterValidator::initAttributeAndMatchFlagsMap(){ + m_attributeAndMatchFlagsMap[MessageFilterValidatorFactory::ATTRIBUTE_TYPE] = m_typeMatchFlagVec; + m_attributeAndMatchFlagsMap[MessageFilterValidatorFactory::ATTRIBUTE_ID] = m_idMatchFlagVec; + m_attributeAndMatchFlagsMap[MessageFilterValidatorFactory::ATTRIBUTE_FOLDER] = m_folderIdMatchFlagVec; + m_attributeAndMatchFlagsMap[MessageFilterValidatorFactory::ATTRIBUTE_TIMESTAMP] = m_timestampMatchFlagVec; + m_attributeAndMatchFlagsMap[MessageFilterValidatorFactory::ATTRIBUTE_FROM] = m_fromMatchFlagVec; + m_attributeAndMatchFlagsMap[MessageFilterValidatorFactory::ATTRIBUTE_CC] = m_ccMatchFlagVec; + m_attributeAndMatchFlagsMap[MessageFilterValidatorFactory::ATTRIBUTE_BCC] = m_bccMatchFlagVec; + m_attributeAndMatchFlagsMap[MessageFilterValidatorFactory::ATTRIBUTE_BODY] = m_bodyMatchFlagVec; + m_attributeAndMatchFlagsMap[MessageFilterValidatorFactory::ATTRIBUTE_IS_READ] = m_isReadMatchFlagVec; + m_attributeAndMatchFlagsMap[MessageFilterValidatorFactory::ATTRIBUTE_PRIORITY] = m_priorityMatchFlagVec; + m_attributeAndMatchFlagsMap[MessageFilterValidatorFactory::ATTRIBUTE_SUBJECT] = m_subjectMatchFlagVec; + m_attributeAndMatchFlagsMap[MessageFilterValidatorFactory::ATTRIBUTE_TO] = m_toMatchFlagVec; + } + + bool MessageFilterValidator::validateAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth){ + bool retVal = false; + + if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_TIMESTAMP)!=0){ + MsgLogError(">>> [ERROR] Not Supported attribute :[" << attrName << "]"); + return false; + } + + retVal = FilterValidator::validateAttributeRange(attrName, initialValue, endValue, depth); + return retVal; + } + + + bool MessageFilterValidator::vectorContains(std::vector& vec, std::string& value){ + std::vector::iterator it; + for(it=vec.begin(); itbegin(); iter!=values->end(); iter++){ + AnyPtr value = *iter; + if(validateAttributeEach(attrName, value, matchFlag, depth) == false){ + MsgLogWanning(">>>[Warning] attrName:[" << attrName << "] is invalid value:[" << value->toString() << "]"); + return false; + } + } + + retBool = FilterValidator::validateAttribute(attrName, values, matchFlag, caseSensitive, depth); + LogDebug(">>> retBool:" << retBool); + return retBool; + } + + bool MessageFilterValidator::validateAttributeEach(std::string& attrName,Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth){ + LogDebug("<<< attrName:[" << attrName << "], value:[" << value->toString() << "]"); + + if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_TYPE)==0){ + if(m_isTypeSetted == true){ + MsgLogError(">>> [ERROR] duplicated type :[" << attrName << "], value:[" << + value->toString()<< "]"); + return false; + }else{ + m_isTypeSetted = true; + } + } + + std::vector vec = m_attributeAndMatchFlagsMap.find(attrName)->second; + + if(vectorContains(vec, matchFlag)==false){ + MsgLogWanning(">>>[Waning]MatchFlag check fail unsupported flag:[" << matchFlag << "] for Attribute:[" << attrName << "]"); + return false; + } + + LogDebug(">>> return true"); + return true; + } + + } //namespace Messaging + } + +} diff --git a/src/platform/API/Messaging/MessageFilterValidator.h b/src/platform/API/Messaging/MessageFilterValidator.h new file mode 100755 index 0000000..f4a9150 --- /dev/null +++ b/src/platform/API/Messaging/MessageFilterValidator.h @@ -0,0 +1,82 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * MessageFilterValidator.h + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#ifndef MESSAGEFILTERVALIDATOR_H_ +#define MESSAGEFILTERVALIDATOR_H_ + +#include +#include + +namespace TizenApis { + + namespace Platform { + + namespace Messaging { + + class MessageFilterValidator: public Api::Tizen::FilterValidator { + private: + bool m_isTypeSetted; + + std::vector m_typeMatchFlagVec; + std::vector m_idMatchFlagVec; + std::vector m_folderIdMatchFlagVec; + std::vector m_timestampMatchFlagVec; + std::vector m_fromMatchFlagVec; + std::vector m_toMatchFlagVec; + std::vector m_ccMatchFlagVec; + std::vector m_bccMatchFlagVec; + std::vector m_bodyMatchFlagVec; + std::vector m_isReadMatchFlagVec; + std::vector m_priorityMatchFlagVec; + std::vector m_subjectMatchFlagVec; + + std::map > m_attributeAndMatchFlagsMap; + + public: + MessageFilterValidator(Api::Tizen::PropertyStructArray properties, + Api::Tizen::MatchFlagStrArray matchFlag, Api::Tizen::PrimitiveType idType); + + virtual ~MessageFilterValidator(); + + // validate AttributeRangeFilter + virtual bool validateAttributeRange(std::string& attrName, + Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth=0); + + virtual bool validateAttribute(std::string& attrName, Api::Tizen::AnyArrayPtr& values, + std::string& matchFlag, bool caseSensitive, int depth=0); + + protected: + bool validateAttributeEach(std::string& attrName,Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth); + + private : + void initMatchFlagVectors(); + void initAttributeAndMatchFlagsMap(); + + bool vectorContains(std::vector& vec, std::string& value); + + }; + + typedef DPL::SharedPtr MessageFilterValidatorPtr; + } + } +} +#endif /* MESSAGEFILTERVALIDATOR_H_ */ diff --git a/src/platform/API/Messaging/MessageFilterValidatorFactory.cpp b/src/platform/API/Messaging/MessageFilterValidatorFactory.cpp new file mode 100755 index 0000000..2bec89e --- /dev/null +++ b/src/platform/API/Messaging/MessageFilterValidatorFactory.cpp @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * MessagingFilterValidatorFactory.cpp + * + * Created on: 2011. 10. 27. + * Author: sangtai + */ + +#include "MessageFilterValidatorFactory.h" + +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + const std::string MessageFilterValidatorFactory::ATTRIBUTE_ID = "id"; + const std::string MessageFilterValidatorFactory::ATTRIBUTE_TYPE = "type"; + const std::string MessageFilterValidatorFactory::ATTRIBUTE_FOLDER = "folderId"; + const std::string MessageFilterValidatorFactory::ATTRIBUTE_TIMESTAMP = "timestamp"; + const std::string MessageFilterValidatorFactory::ATTRIBUTE_FROM = "from"; + const std::string MessageFilterValidatorFactory::ATTRIBUTE_TO = "to"; + const std::string MessageFilterValidatorFactory::ATTRIBUTE_CC = "cc"; + const std::string MessageFilterValidatorFactory::ATTRIBUTE_BCC = "bcc"; + const std::string MessageFilterValidatorFactory::ATTRIBUTE_BODY = "body"; + const std::string MessageFilterValidatorFactory::ATTRIBUTE_IS_READ = "isRead"; + const std::string MessageFilterValidatorFactory::ATTRIBUTE_PRIORITY = "priority"; + const std::string MessageFilterValidatorFactory::ATTRIBUTE_SUBJECT = "subject"; + + std::string MessageFilterValidatorFactory::MATCH_EXACTLY = "EXACTLY"; + std::string MessageFilterValidatorFactory::MATCH_CONTAINS = "CONTAINS"; + std::string MessageFilterValidatorFactory::MATCH_STARTSWITH = "STARTSWITH"; + std::string MessageFilterValidatorFactory::MATCH_ENDSWITH = "ENDSWITH"; + + static PropertyStructArray properties = + { + {MessageFilterValidatorFactory::ATTRIBUTE_ID.c_str(), Api::Tizen::PrimitiveType_String}, + {MessageFilterValidatorFactory::ATTRIBUTE_TYPE.c_str(), Api::Tizen::PrimitiveType_String}, + {MessageFilterValidatorFactory::ATTRIBUTE_FOLDER.c_str(), Api::Tizen::PrimitiveType_String}, + {MessageFilterValidatorFactory::ATTRIBUTE_TIMESTAMP.c_str(), Api::Tizen::PrimitiveType_Time}, + {MessageFilterValidatorFactory::ATTRIBUTE_FROM.c_str(), Api::Tizen::PrimitiveType_String}, + {MessageFilterValidatorFactory::ATTRIBUTE_TO.c_str(), Api::Tizen::PrimitiveType_String}, + {MessageFilterValidatorFactory::ATTRIBUTE_CC.c_str(), Api::Tizen::PrimitiveType_String}, + {MessageFilterValidatorFactory::ATTRIBUTE_BCC.c_str(), Api::Tizen::PrimitiveType_String}, + {MessageFilterValidatorFactory::ATTRIBUTE_BODY.c_str(), Api::Tizen::PrimitiveType_String}, + {MessageFilterValidatorFactory::ATTRIBUTE_IS_READ.c_str(), Api::Tizen::PrimitiveType_Boolean}, + {MessageFilterValidatorFactory::ATTRIBUTE_PRIORITY.c_str(), Api::Tizen::PrimitiveType_Boolean}, + {MessageFilterValidatorFactory::ATTRIBUTE_SUBJECT.c_str(), Api::Tizen::PrimitiveType_String}, + {0, Api::Tizen::PrimitiveType_Notype} + }; + + static MatchFlagStrArray matchFlag{ + "EXACTLY", + "CONTAINS", + "STARTSWITH", + "ENDSWITH", + 0 + }; + + MessageFilterValidatorPtr MessageFilterValidatorFactory::getMessageFilterValidator() + { + MessageFilterValidatorPtr theInstance = + MessageFilterValidatorPtr(new MessageFilterValidator(properties, matchFlag, Api::Tizen::PrimitiveType_Int)); + + return theInstance; + } + + } + } //naspace Platform +} //naspace WrtPlugins diff --git a/src/platform/API/Messaging/MessageFilterValidatorFactory.h b/src/platform/API/Messaging/MessageFilterValidatorFactory.h new file mode 100755 index 0000000..e9426db --- /dev/null +++ b/src/platform/API/Messaging/MessageFilterValidatorFactory.h @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * MessagingFilterValidatorFactory.h + * + * Created on: 2011. 10. 27. + * Author: sangtai + */ + +#ifndef MESSAGINGFILTERVALIDATORFACTORY_H_ +#define MESSAGINGFILTERVALIDATORFACTORY_H_ + +#include +#include "MessageFilterValidator.h" + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + class MessageFilterValidatorFactory { + private: + MessageFilterValidatorFactory() + { + } + + public: + static MessageFilterValidatorPtr getMessageFilterValidator(); + + public: + static const std::string ATTRIBUTE_ID; + static const std::string ATTRIBUTE_TYPE; + static const std::string ATTRIBUTE_FOLDER; + static const std::string ATTRIBUTE_TIMESTAMP; + static const std::string ATTRIBUTE_FROM; + static const std::string ATTRIBUTE_TO; + static const std::string ATTRIBUTE_CC; + static const std::string ATTRIBUTE_BCC; + static const std::string ATTRIBUTE_BODY; + static const std::string ATTRIBUTE_IS_READ; + static const std::string ATTRIBUTE_PRIORITY; + static const std::string ATTRIBUTE_SUBJECT; + + static std::string MATCH_EXACTLY; + static std::string MATCH_CONTAINS; + static std::string MATCH_STARTSWITH; + static std::string MATCH_ENDSWITH; + static std::string MATCH_CASESENSITIVE; + }; + + } + } //Platform +} + +#endif /* MESSAGINGFILTERVALIDATORFACTORY_H_ */ diff --git a/src/platform/API/Messaging/MessagePriority.cpp b/src/platform/API/Messaging/MessagePriority.cpp new file mode 100755 index 0000000..dfd278c --- /dev/null +++ b/src/platform/API/Messaging/MessagePriority.cpp @@ -0,0 +1,60 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file MessagePriority.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "MessagePriority.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +MessagePriority::MessagePriority() : + m_priority(NORMAL), + m_validPriority(false) +{ +} + +void MessagePriority::setPriority(MessagePriority::Priority value) +{ + m_priority = value; + m_validPriority = false; +} + +MessagePriority::Priority MessagePriority::getPriority() const +{ + return m_priority; +} + +bool MessagePriority::isPriorityValid() const +{ + return m_validPriority; +} + +void MessagePriority::setPriorityValid(bool state) +{ + m_validPriority = state; +} +} +} +} diff --git a/src/platform/API/Messaging/MessagePriority.h b/src/platform/API/Messaging/MessagePriority.h new file mode 100755 index 0000000..fad0e85 --- /dev/null +++ b/src/platform/API/Messaging/MessagePriority.h @@ -0,0 +1,78 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @file MessagePriority.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef MESSAGEPRIORITY_H +#define MESSAGEPRIORITY_H + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class MessagePriority +{ + public: + enum Priority + { + LOW, + NORMAL, + HIGH + }; + + public: + MessagePriority(); + + /** + * setter of MessagePriority value + */ + void setPriority(Priority value); + + /** + * getter of MessagePriority value + */ + Priority getPriority() const; + + /** + * check MessagePriority validity + * */ + bool isPriorityValid() const; + + /** + * set MessagePriority validity + * */ + void setPriorityValid(bool state); + + private: + /** + * MessagePriority value + */ + Priority m_priority; + + /** + * information if abstract message MessagePriority has been changed and need update + * in low level + */ + bool m_validPriority; +}; +} +} +} +#endif // MESSAGEPRIORITY_H diff --git a/src/platform/API/Messaging/MessageProperties.h b/src/platform/API/Messaging/MessageProperties.h new file mode 100755 index 0000000..05a978e --- /dev/null +++ b/src/platform/API/Messaging/MessageProperties.h @@ -0,0 +1,56 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author + */ + +#ifndef WRTPLUGINS_API_MESSAGING_PROPERTIES_H_ +#define WRTPLUGINS_API_MESSAGING_PROPERTIES_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +struct MessagingProperties { + + std::string subject; + std::vector< std::string > to; + std::vector< std::string > cc; + std::vector< std::string > bcc; + std::string plainBody; + std::string htmlBody; + bool priority; + + MessagingProperties() : + priority(false) + { + + } +}; + +typedef DPL::SharedPtr MessagingPropertiesPtr; + +}//Messaging +} // Api +} + +#endif //WRTPLUGINS_API_MESSAGING_PROPERTIES_H_ \ No newline at end of file diff --git a/src/platform/API/Messaging/MessagingFactory.cpp b/src/platform/API/Messaging/MessagingFactory.cpp new file mode 100755 index 0000000..391e455 --- /dev/null +++ b/src/platform/API/Messaging/MessagingFactory.cpp @@ -0,0 +1,45 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "MessagingFactory.h" +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +using namespace TizenApis::Platform::Messaging; + + +IMessagingServiceManagerPtr MessagingFactory::getMessagingServiceManager() { + return IMessagingServiceManagerPtr( new MessagingServiceManager() ); +} + +MessagingFactory& MessagingFactory::getInstance() { + static MessagingFactory theInstance; + return theInstance; +} + +MessagingFactory::MessagingFactory() { +} + +MessagingFactory::~MessagingFactory(){ +} + +} +} +} + diff --git a/src/platform/API/Messaging/MessagingFactory.h b/src/platform/API/Messaging/MessagingFactory.h new file mode 100755 index 0000000..37675d6 --- /dev/null +++ b/src/platform/API/Messaging/MessagingFactory.h @@ -0,0 +1,43 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#ifndef WRTPLUGINS_API_MESSAGING_FACTORY_H_ +#define WRTPLUGINS_API_MESSAGING_FACTORY_H_ + +#include +#include "IMessagingServiceManager.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class MessagingFactory : DPL::Noncopyable +{ +public: + IMessagingServiceManagerPtr getMessagingServiceManager(); + static MessagingFactory& getInstance(); + +protected: + MessagingFactory(); + ~MessagingFactory(); +}; + + +} +} +} + +#endif //WRTPLUGINS_API_MESSAGING_FACTORY_H_ + diff --git a/src/platform/API/Messaging/MmsSlide.cpp b/src/platform/API/Messaging/MmsSlide.cpp new file mode 100755 index 0000000..ff557f4 --- /dev/null +++ b/src/platform/API/Messaging/MmsSlide.cpp @@ -0,0 +1,172 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * @file MmsSlide.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include "MmsSlide.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +MmsSlide::MmsSlide() : m_duration(0) +{ +} + +MmsSlide::~MmsSlide() +{ +} + +unsigned long MmsSlide::getDuration() const +{ + return m_duration; +} + +void MmsSlide::setDuration(Ulong duration) +{ + m_duration = duration; +} + +const std::string& MmsSlide::getImageFilename() const +{ + return m_image.getFilename(); +} + +void MmsSlide::setImageFilename(const std::string& filename) +{ + m_image.setFilename(filename); +} + +unsigned long MmsSlide::getImageBegin() const +{ + return m_image.getStartTime(); +} + +void MmsSlide::setImageBegin(Ulong value) +{ + m_image.setStartTime(value); +} + +unsigned long MmsSlide::getImageEnd() const +{ + return m_image.getEndTime(); +} + +void MmsSlide::setImageEnd(Ulong value) +{ + m_image.setEndTime(value); +} + +const std::string& MmsSlide::getAudioFilename() const +{ + return m_audio.getFilename(); +} + +void MmsSlide::setAudioFilename(const std::string& filename) +{ + m_audio.setFilename(filename); +} + +unsigned long MmsSlide::getAudioBegin() const +{ + return m_audio.getStartTime(); +} + +void MmsSlide::setAudioBegin(Ulong value) +{ + m_audio.setStartTime(value); +} + +unsigned long MmsSlide::getAudioEnd() const +{ + return m_audio.getEndTime(); +} + +void MmsSlide::setAudioEnd(Ulong value) +{ + m_audio.setEndTime(value); +} + +const std::string& MmsSlide::getTextFilename() const +{ + return m_text.getFilename(); +} + +void MmsSlide::setTextFilename(const std::string& filename) +{ + m_text.setFilename(filename); +} + +unsigned long MmsSlide::getTextBegin() const +{ + return m_text.getStartTime(); +} + +void MmsSlide::setTextBegin(Ulong value) +{ + m_text.setStartTime(value); +} + +unsigned long MmsSlide::getTextEnd() const +{ + return m_text.getEndTime(); +} + +void MmsSlide::setTextEnd(Ulong value) +{ + m_text.setEndTime(value); +} + +const std::string& MmsSlide::getVideoFilename() const +{ + return m_video.getFilename(); +} + +void MmsSlide::setVideoFilename(const std::string& filename) +{ + m_video.setFilename(filename); +} + +unsigned long MmsSlide::getVideoBegin() const +{ + return m_video.getStartTime(); +} + +void MmsSlide::setVideoBegin(Ulong value) +{ + m_video.setStartTime(value); +} + +unsigned long MmsSlide::getVideoEnd() const +{ + return m_video.getEndTime(); +} + +void MmsSlide::setVideoEnd(Ulong value) +{ + m_video.setEndTime(value); +} +} +} +} + diff --git a/src/platform/API/Messaging/MmsSlide.h b/src/platform/API/Messaging/MmsSlide.h new file mode 100755 index 0000000..decd0a7 --- /dev/null +++ b/src/platform/API/Messaging/MmsSlide.h @@ -0,0 +1,90 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * @file MmsSlide.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef MMS_SLIDE_H +#define MMS_SLIDE_H + +#include "IMmsSlide.h" +#include "MmsSlideProperty.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class MmsSlide : public virtual IMmsSlide +{ + public: + MmsSlide(); + + virtual ~MmsSlide(); + + //duration + virtual Ulong getDuration() const; + virtual void setDuration(Ulong duration); + + //image + virtual const std::string& getImageFilename() const; + virtual void setImageFilename(const std::string& filename); + virtual Ulong getImageBegin() const; + virtual void setImageBegin(Ulong value); + virtual Ulong getImageEnd() const; + virtual void setImageEnd(Ulong value); + + //audio + virtual const std::string& getAudioFilename() const; + virtual void setAudioFilename(const std::string& filename); + virtual Ulong getAudioBegin() const; + virtual void setAudioBegin(Ulong value); + virtual Ulong getAudioEnd() const; + virtual void setAudioEnd(Ulong value); + + //text + virtual const std::string& getTextFilename() const; + virtual void setTextFilename(const std::string& filename); + virtual Ulong getTextBegin() const; + virtual void setTextBegin(Ulong value); + virtual Ulong getTextEnd() const; + virtual void setTextEnd(Ulong value); + + //video + virtual const std::string& getVideoFilename() const; + virtual void setVideoFilename(const std::string& filename); + virtual Ulong getVideoBegin() const; + virtual void setVideoBegin(Ulong value); + virtual Ulong getVideoEnd() const; + virtual void setVideoEnd(Ulong value); + + private: + Ulong m_duration; + + MmsSlideProperty m_image; + MmsSlideProperty m_audio; + MmsSlideProperty m_text; + MmsSlideProperty m_video; +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/MmsSlideProperty.cpp b/src/platform/API/Messaging/MmsSlideProperty.cpp new file mode 100755 index 0000000..9731499 --- /dev/null +++ b/src/platform/API/Messaging/MmsSlideProperty.cpp @@ -0,0 +1,74 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * @file MmsSlideProperty.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include "MmsSlideProperty.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +MmsSlideProperty::MmsSlideProperty() : + m_filename(""), + m_startTime(0), + m_endTime(0) +{ +} + +MmsSlideProperty::~MmsSlideProperty() +{ +} + +const std::string& MmsSlideProperty::getFilename() const +{ + return m_filename; +} + +unsigned long MmsSlideProperty::getStartTime() const +{ + return m_startTime; +} + +unsigned long MmsSlideProperty::getEndTime() const +{ + return m_endTime; +} + +void MmsSlideProperty::setFilename(const std::string& value) +{ + m_filename = value; +} + +void MmsSlideProperty::setStartTime(Ulong value) +{ + m_startTime = value; +} + +void MmsSlideProperty::setEndTime(Ulong value) +{ + m_endTime = value; +} +} +} +} diff --git a/src/platform/API/Messaging/MmsSlideProperty.h b/src/platform/API/Messaging/MmsSlideProperty.h new file mode 100755 index 0000000..4b7ae61 --- /dev/null +++ b/src/platform/API/Messaging/MmsSlideProperty.h @@ -0,0 +1,87 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * @file MmsSlideProperty.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef MMS_SLIDE_PROPERTY_H +#define MMS_SLIDE_PROPERTY_H + +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class MmsSlideProperty +{ + private: + typedef unsigned long Ulong; + + private: + + std::string m_filename; + + Ulong m_startTime; + + Ulong m_endTime; + + public: + + MmsSlideProperty(); + + virtual ~MmsSlideProperty(); + + /** + * getters for filename + * */ + virtual const std::string& getFilename() const; + + /** + * getters for startTime + * */ + virtual Ulong getStartTime() const; + + /** + * getters for endTime + * */ + virtual Ulong getEndTime() const; + + /** + * setters for filename + * */ + virtual void setFilename(const std::string& value); + + /** + * setters for start time + * */ + virtual void setStartTime(Ulong value); + + /** + * setters for end time + * */ + virtual void setEndTime(Ulong value); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/MmsSlides.cpp b/src/platform/API/Messaging/MmsSlides.cpp new file mode 100755 index 0000000..8171a01 --- /dev/null +++ b/src/platform/API/Messaging/MmsSlides.cpp @@ -0,0 +1,104 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file MmsSlides.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include "MmsSlides.h" +#include "MmsSlide.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +MmsSlides::MmsSlides() : m_valid(false) +{ +} + +MmsSlides::~MmsSlides() +{ +} + +bool MmsSlides::checkSlidesValidity() const +{ + return m_valid; +} + +void MmsSlides::setSlidesValidity(bool state) +{ + m_valid = state; +} + +void MmsSlides::setSlides(const std::vector& slides) +{ + m_slides = slides; +} + +IMmsSlidePtr MmsSlides::createEmptySlide() const +{ + IMmsSlide* slide = NULL; + slide = new MmsSlide; + + return IMmsSlidePtr(slide); +} + +void MmsSlides::addSlide(const IMmsSlidePtr& slide) +{ + m_slides.push_back(slide); +} + +size_t MmsSlides::getSlideCount() const +{ + return m_slides.size(); +} + +IMmsSlidePtr MmsSlides::getSlide(size_t nb) const +{ + if (nb >= m_slides.size()) { + //TODO -exception? + } + return m_slides[nb]; +} + +std::vector MmsSlides::getSlides() const +{ + return m_slides; +} + +void MmsSlides::replaceSlide(size_t pos, + const IMmsSlidePtr& slide) +{ + if (pos >= m_slides.size()) { + //TODO + } else { + //m_slides.erase(m_slides.begin()+pos); + m_slides[pos] = slide; + } +} + +void MmsSlides::removeSlide(size_t pos) +{ +} +} +} +} diff --git a/src/platform/API/Messaging/MmsSlides.h b/src/platform/API/Messaging/MmsSlides.h new file mode 100755 index 0000000..5bfaa76 --- /dev/null +++ b/src/platform/API/Messaging/MmsSlides.h @@ -0,0 +1,75 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file MmsSlides.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef MMS_SLIDES_H +#define MMS_SLIDES_H + +#include "IMmsSlides.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class MmsSlides : + virtual public IMmsSlides +{ + public: + + MmsSlides(); + + virtual ~MmsSlides(); + + virtual IMmsSlidePtr createEmptySlide() const; + + virtual bool checkSlidesValidity() const; + + virtual void setSlidesValidity(bool state); + + virtual void setSlides(const std::vector& slides); + + virtual void addSlide(const IMmsSlidePtr& slide); + + virtual size_t getSlideCount() const; + + virtual IMmsSlidePtr getSlide(size_t nb) const; + + virtual std::vector getSlides() const; + + virtual void replaceSlide(size_t pos, + const IMmsSlidePtr& slide); + + virtual void removeSlide(size_t pos); + + private: + + bool m_valid; + + std::vector m_slides; +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/Recipient.cpp b/src/platform/API/Messaging/Recipient.cpp new file mode 100755 index 0000000..2a6dcb5 --- /dev/null +++ b/src/platform/API/Messaging/Recipient.cpp @@ -0,0 +1,213 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Recipient.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include +#include +#include +#include "Recipient.h" + +using namespace std; +using namespace WrtDeviceApis::Commons; + +namespace { +const static string emptyString; +} + +namespace TizenApis { +namespace Api { +namespace Messaging { + +Recipients::Recipients() : + m_validRecipients(false) +{ +} + +Recipients::Recipients(const vector& value) : + m_validRecipients(false) +{ + m_recipients = value; +} + +Recipients::~Recipients() +{ +} + +bool Recipients::isValid() const +{ + return m_validRecipients; +} + +void Recipients::setValid(bool state) +{ + m_validRecipients = state; +} + +void Recipients::setRecipients(const vector& value) +{ + m_recipients = value; + m_validRecipients = false; +} + +void Recipients::setRecipients(const std::string& value) +{ + vector tmp = split(value, ';'); + setRecipients(tmp); +} + +void Recipients::setRecipient(const size_t index, + const string& value) +{ + if (index >= m_recipients.size()) { + Throw(OutOfRangeException); + return; + } + m_recipients[index] = value; + m_validRecipients = false; +} + +void Recipients::setRecipientWithExpand(const size_t index, + const std::string& value) +{ + if (index >= m_recipients.size()) { + m_recipients.resize(index + 1, emptyString); + } + m_recipients[index] = value; + m_validRecipients = false; +} + +vector Recipients::getRecipients() const +{ + return m_recipients; +} + +const vector& Recipients::getRecipientsRef() const +{ + return m_recipients; +} + +string Recipients::getRecipient(const size_t index) const +{ + if (index >= m_recipients.size()) { + Throw(OutOfRangeException); + return ""; + } + return m_recipients[index]; +} + +void Recipients::appendRecipient(const string & value) +{ + vector tmp = split(value, ';'); + m_recipients.insert(m_recipients.end(), tmp.begin(), tmp.end()); + m_validRecipients = false; +} + +void Recipients::removeRecipient(const size_t position) +{ + if (position >= m_recipients.size()) { + Throw(WrtDeviceApis::Commons::OutOfRangeException); + } else { + m_recipients.erase(m_recipients.begin() + position); + m_validRecipients = false; + } +} + +void Recipients::removeRecipient(const string & value) +{ + m_recipients.erase( + remove(m_recipients.begin(), m_recipients.end(), value), + m_recipients.end()); + m_validRecipients = false; +} + +string Recipients::join(char delimiter) const +{ + string retVal; + for (size_t i = 0; i < m_recipients.size(); i++) { + retVal += m_recipients[i] + delimiter; + } + return retVal; +} + +vector Recipients::split(const string& input, + char delimiter) +{ + vector ret; + stringstream stream(input); + string item; + while (getline(stream, item, delimiter)) { + ret.push_back(item); + } + return ret; +} + +size_t Recipients::getRecipientSize() const +{ + return m_recipients.size(); +} + +bool Recipients::operator !=(const Recipients& arg) const +{ + if (m_recipients == arg.m_recipients) { + return true; + } + return false; +} + +Recipients & Recipients::operator +=(const Recipients& val) +{ + const vector& tmp = val.getRecipientsRef(); + m_recipients.insert(m_recipients.end(), tmp.begin(), tmp.end()); + m_validRecipients = false; + return *this; +} + +Recipients & Recipients::operator -=(const Recipients& val) +{ + //check if recipients are inside list + vector l_recipients = m_recipients; + vector l_toDelete = val.getRecipients(); + sort(l_recipients.begin(), l_recipients.end()); + sort(l_toDelete.begin(), l_toDelete.end()); + if (!includes(l_recipients.begin(), l_recipients.end(), l_toDelete.begin(), + l_toDelete.end())) { + LogError("lack of recipient to delete from main variable"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + //delete recipients + vector::const_iterator it = l_toDelete.begin(); + const vector::const_iterator endIt = l_toDelete.end(); + while (it != endIt) { + m_recipients.erase( + remove(m_recipients.begin(), + m_recipients.end(), *it), m_recipients.end()); + ++it; + } + m_validRecipients = false; + return *this; +} +} +} +} diff --git a/src/platform/API/Messaging/Recipient.h b/src/platform/API/Messaging/Recipient.h new file mode 100755 index 0000000..8c3f25e --- /dev/null +++ b/src/platform/API/Messaging/Recipient.h @@ -0,0 +1,115 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Recipient.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef RECIPIENT_H +#define RECIPIENT_H + +#include "IMessagingTypes.h" +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class Recipients +{ + private: // fields + + /** + * recipient value + */ + std::vector m_recipients; + + bool m_validRecipients; + + public: // methods + + Recipients(); + + explicit Recipients(const std::vector& value); + + virtual ~Recipients(); + + /** + * information if abstract message to recipient has been changed and + * need update in low level + */ + bool isValid() const; + + void setValid(bool state); + + /** + * setter of recipient value + */ + void setRecipients(const std::vector& value); + + void setRecipients(const std::string& value); + + void setRecipient(const size_t index, + const std::string& value); + + void setRecipientWithExpand(const size_t index, + const std::string& value); + + /** + * getter of recipient value + */ + std::vector getRecipients() const; + + const std::vector& getRecipientsRef() const; + + std::string getRecipient(const size_t index) const; + + void appendRecipient(const std::string & value); + + void removeRecipient(const size_t position); + + void removeRecipient(const std::string & value); + + size_t getRecipientSize() const; + + bool operator !=(const Recipients& arg) const; + + Recipients & operator +=(const Recipients& val); + + Recipients & operator -=(const Recipients& val); + + std::string join(char delimiter = ';') const; + + private: + + std::vector split(const std::string& input, + char delimiter); +}; + +typedef DPL::SharedPtr RecipientsPtr; +} +} +} +#endif diff --git a/src/platform/API/Messaging/ReqReceiverMessage.cpp b/src/platform/API/Messaging/ReqReceiverMessage.cpp new file mode 100755 index 0000000..a3cf2b1 --- /dev/null +++ b/src/platform/API/Messaging/ReqReceiverMessage.cpp @@ -0,0 +1,654 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @file ReqReceiverMessage.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include +#include "ReqReceiverMessage.h" +#include "IMessaging.h" +#include "IMessage.h" + +#include "MessageFilterValidatorFactory.h" +#include "ConversationFilterValidatorFactory.h" +#include "FolderFilterValidatorFactory.h" + + +using namespace std; +using namespace TizenApis::Api::Tizen; +using namespace TizenApis::Platform::Messaging; +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +ReqReceiverMessage::ReqReceiverMessage() : + EventSendMessageReqReceiver(ThreadEnum::MESSAGING_THREAD), + EventUpdateMessageReqReceiver(ThreadEnum::MESSAGING_THREAD), + EventDeleteMessageReqReceiver(ThreadEnum::MESSAGING_THREAD), + EventDeleteMessagesReqReceiver(ThreadEnum::MESSAGING_THREAD), + EventUpdateMessagesReqReceiver(ThreadEnum::MESSAGING_THREAD), + EventQueryMessagesReqReceiver(ThreadEnum::MESSAGING_THREAD), + EventGetConversationIdReqReceiver(ThreadEnum::MESSAGING_THREAD), + EventQueryConversationsReqReceiver(ThreadEnum::MESSAGING_THREAD), + EventDeleteConversationsReqReceiver(ThreadEnum::MESSAGING_THREAD), + EventQueryFoldersReqReceiver(ThreadEnum::MESSAGING_THREAD), + EventMessagingServiceReqReceiver(ThreadEnum::MESSAGING_THREAD) +{ + LogDebug("create receiver for messaging"); +} + +ReqReceiverMessage::~ReqReceiverMessage() +{ +} + +void ReqReceiverMessage::sendMessage(const EventSendMessagePtr& event) +{ + LogDebug("enter"); + EventSendMessageReqReceiver::PostRequest(event); +} + +void ReqReceiverMessage::updateMessage(const EventUpdateMessagePtr& event) +{ + LogDebug("enter"); + EventUpdateMessageReqReceiver::PostRequest(event); +} + +void ReqReceiverMessage::deleteMessage(const EventDeleteMessagePtr& event) +{ + LogDebug("enter"); + EventDeleteMessageReqReceiver::PostRequest(event); +} + +void ReqReceiverMessage::deleteMessages(const EventDeleteMessagesPtr& event) +{ + LogDebug("enter"); + EventDeleteMessagesReqReceiver::PostRequest(event); +} + +void ReqReceiverMessage::updateMessages(const EventUpdateMessagesPtr& event) +{ + LogDebug("enter"); + EventUpdateMessagesReqReceiver::PostRequest(event); +} + +void ReqReceiverMessage::queryMessages(const EventQueryMessagesPtr& event) +{ + LogDebug("enter"); + EventQueryMessagesReqReceiver::PostRequest(event); +} + + +void ReqReceiverMessage::getConversationId(const EventGetConversationIdPtr& event) +{ + LogDebug("enter"); + EventGetConversationIdReqReceiver::PostRequest(event); +} + +void ReqReceiverMessage::queryConversations(const EventQueryConversationsPtr& event) +{ + LogDebug("enter"); + EventQueryConversationsReqReceiver::PostRequest(event); +} + +void ReqReceiverMessage::deleteConversations(const EventDeleteConversationsPtr& event) +{ + LogDebug("enter"); + EventDeleteConversationsReqReceiver::PostRequest(event); +} + +void ReqReceiverMessage::queryFolders(const EventQueryFoldersPtr& event) +{ + LogDebug("enter"); + EventQueryFoldersReqReceiver::PostRequest(event); +} + +void ReqReceiverMessage::loadMessageBody(const EventMessagingServicePtr& event) +{ + LogDebug("enter"); + EventMessagingServiceReqReceiver::PostRequest(event); +} + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +void ReqReceiverMessage::loadMessageAttachment(const EventMessagingServicePtr& event) +{ + LogDebug("enter"); + EventMessagingServiceReqReceiver::PostRequest(event); +} +#endif + +void ReqReceiverMessage::sync(const EventMessagingServicePtr& event) +{ + LogDebug("enter"); + EventMessagingServiceReqReceiver::PostRequest(event); +} + +void ReqReceiverMessage::syncFolder(const EventMessagingServicePtr& event) +{ + LogDebug("enter"); + EventMessagingServiceReqReceiver::PostRequest(event); +} + +void ReqReceiverMessage::OnRequestReceived(const EventSendMessagePtr& event) +{ + LogDebug("enter"); + + Try { + IMessagePtr msg = event->msg; + //this prevents calling BONDI, Tizen callback immidiately after leaving this function + //callback will be called after receving platform callback. + msg->setRequestReceiver(this); + msg->setSendMessageEvent(event); + if (!event->checkCancelled()) { + event->setCancelAllowed(false); + event->switchToManualAnswer(); + int handle = msg->send(); + LogDebug("handle : " << handle); + if (event->opId && event->m_messagingService) + { + event->m_messagingService->setHandleToOpId(event->opId, handle); + } + } else { + event->setCancelAllowed(true); + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + WrtDeviceApis::Commons::EventRequestReceiver::ManualAnswer(event); + } +} + +void ReqReceiverMessage::OnRequestReceived(const EventUpdateMessagePtr& event) +{ + LogDebug("enter"); + + Try { + IMessagePtr msg = event->msg; + if (!event->checkCancelled()) { + event->setCancelAllowed(false); + msg->update(true); + } else { + event->setCancelAllowed(true); + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + MsgLogError("platform exception"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + } +} + +void ReqReceiverMessage::OnRequestReceived(const EventDeleteMessagePtr& event) +{ + LogDebug("enter"); + + Try { + IMessagePtr msg = event->msg; + msg->remove(); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + MsgLogError("platform exception"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + } +} + +bool ReqReceiverMessage::validateFilter(const Tizen::FilterPtr& filter){ + LogDebug("<<<"); + + bool retBool = false; + + if(filter != NULL){ + MessageFilterValidatorPtr validator = + MessageFilterValidatorFactory::getMessageFilterValidator(); + + FilterValidatorPtr filterValidator = DPL::StaticPointerCast(validator); + retBool = filter->validate(filterValidator); + LogDebug("retBool:" << retBool); + if(retBool == false){ + MsgLogError(">>> Validate FAIL InvalidArgumentException"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + }else{ + LogDebug("filter is NULL"); + retBool = false; + } + + LogDebug(">>> retBool:" << retBool); + return retBool; + +} + +void ReqReceiverMessage::OnRequestReceived(const EventDeleteMessagesPtr& event) +{ + LogDebug("enter"); + + Try { + Tizen::FilterPtr filter = event->getFilter(); + if(filter != NULL){ + bool isValidFilter = validateFilter(filter); + if(isValidFilter == false){ + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + event->msgArray = IMessaging::getInstance().findMessages(event->getFilter()); + } + + std::vector msg = event->msgArray; + LogDebug("msg.size()" << msg.size()); + + int vecSize = msg.size(); + for(int i=0; i < vecSize; i++){ + int type = msg[i]->getMessageType(); + std::string id = msg[i]->getId(); + MsgLogError("type :"<getBody()); + msg[i]->remove(); + }//for + }Catch(WrtDeviceApis::Commons::PlatformException) { + MsgLogError("platform exception"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + } +} + +void ReqReceiverMessage::OnRequestReceived(const EventUpdateMessagesPtr& event) +{ + LogDebug("enter"); + + Try { + std::vector msg = event->msgArray; + LogDebug("msg.size()" << msg.size()); + int vecSize = msg.size(); + for(int i=0; i < vecSize; i++) + { +// int type = msg[i]->getMessageType(); + std::string id = msg[i]->getId(); + msg[i]->updateIsRead(); + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + MsgLogError("platform exception"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + } +} + +void ReqReceiverMessage::OnRequestReceived(const EventQueryMessagesPtr& event) +{ + LogDebug("<<<"); + + Try { + + vector msgs; + + //check filter validation + Tizen::FilterPtr filter = event->getFilter(); + bool isValidFilter = validateFilter(filter); + if(isValidFilter == false){ + MsgLogError("[ERROR]this filter is invalid"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + // using filter + vector tmp = IMessaging::getInstance().findMessages(event->getFilter(), event->getSortMode(), event->getLimit(), event->getOffset()); + msgs.insert(msgs.end(), tmp.begin(), tmp.end()); + event->msgs = msgs; + + }Catch(WrtDeviceApis::Commons::PlatformException) { + MsgLogError("platform exception"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + }Catch(WrtDeviceApis::Commons::InvalidArgumentException){ + MsgLogError("InvalidArgumentException"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::InvalidArgumentException); + } +} + +void ReqReceiverMessage::OnRequestReceived(const EventGetConversationIdPtr& event) +{ + LogDebug("enter"); + + Try { + Api::Messaging::IMessagePtr msg = event->getConversationMsgPtr(); + Api::Messaging::MessageType msgType = msg->getMessageType(); + unsigned int msgId = 0; + + if (msgType == EMAIL) + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + msgId = email->getUID(); + + } + else + { + msgId = msg->convertId(msg->getId()); + } + + int conversationId = IMessaging::getInstance().getConversationId(msgId, msgType); + LogDebug("Cond Id:" << conversationId); + event->setConversationId(conversationId); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + MsgLogError("platform exception"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + } +} + +void ReqReceiverMessage::OnRequestReceived(const EventQueryConversationsPtr& event) +{ + LogDebug("<<<"); + + Try + { + //check filter validation + Tizen::FilterPtr filter = event->getFilter(); + if(filter != NULL){ + ConversationFilterValidatorPtr validator = + ConversationFilterValidatorFactory::getConversationFilterValidator(); + + FilterValidatorPtr filterValidator = DPL::StaticPointerCast(validator); + bool isValidFilter = filter->validate(filterValidator); + if(isValidFilter == false){ + MsgLogError("[ERROR]Filter is Invalid"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + } + + vector tmp = IMessaging::getInstance().queryConversations(event->getSortMode(), event->getFilter(), event->getLimit(), event->getOffset()); + event->addConversations(tmp); + + } + Catch(WrtDeviceApis::Commons::PlatformException) + { + MsgLogError("platform exception"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) + { + MsgLogError("InvalidArgumentException"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::InvalidArgumentException); + } +} + +void ReqReceiverMessage::OnRequestReceived(const EventMessagingServicePtr& event) +{ + LogDebug("enter : EventMessagingServicePtr"); + + Try { + LogDebug("event type :" << event->getEventType() ); + int MessagingServiceEventType = event->getEventType(); + + if (MessagingServiceEventType == EventMessagingService::MESSAGING_SERVICE_EVENT_TYPE_LOAD_MESSAGE_BODY) + { + if (!event->checkCancelled()) { + IMessagePtr msg = event->m_message; + if(msg) + { + msg->setRequestReceiver(this); + msg->setMessagingServiceEvent(event); + + int type = msg->getMessageType(); + LogDebug("message type :" << type); + if ( msg->getMessageType() == Api::Messaging::EMAIL ) + { + IEmailPtr email = MessageFactory::convertToEmail(msg); + event->switchToManualAnswer(); //switch to manual answer; + int handle = email->downloadBody(); + LogDebug("Load Message Body handle : " << handle); + if (event->opId && event->m_messagingService) + { + event->m_messagingService->setHandleToOpId(event->opId, handle); + } + } + } + else { + LogDebug(" invaild message. "); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::InvalidArgumentException); + } + + } + else + { + LogDebug(" Cancel "); + event->setCancelAllowed(true); + } + } +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + else if (MessagingServiceEventType == EventMessagingService::MESSAGING_SERVICE_EVENT_TYPE_LOAD_MESSAGE_ATTACHMENT) + { + if (!event->checkCancelled()) { + IMessagePtr msg = event->m_message; + if(msg) + { + msg->setRequestReceiver(this); + msg->setMessagingServiceEvent(event); + + int type = msg->getMessageType(); + LogDebug("message type :" << type); + if ( msg->getMessageType() == Api::Messaging::EMAIL ) + { + IEmailPtr email = MessageFactory::convertToEmail(msg); + event->switchToManualAnswer(); //switch to manual answer; + email->downloadAttachment(event->m_attachment); + } + else + { + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::InvalidArgumentException); + } + } + } + else + { + LogDebug(" cancel. "); + event->setCancelAllowed(true); + } + + } +#endif + + else if (MessagingServiceEventType == EventMessagingService::MESSAGING_SERVICE_EVENT_TYPE_SYNC) + { + if (event->m_messagingService) + { + if (!event->checkCancelled()) { + int type = event->m_messagingService->getType(); + LogDebug("messaging service type :" << type); + + event->m_messagingService->setRequestReceiver(this); + event->m_messagingService->setMessagingServiceEvent(event); // + + if (type == Api::Messaging::EMAIL) + { + event->switchToManualAnswer(); //switch to manual answer; + LogDebug("privateData->getAccountId() :" << event->m_messagingService->getAccountID()); + + if ( event->m_messagingService->getAccountID() > 0) + { + int handle = event->m_messagingService->sync( event->m_messagingService, event->m_sync_limit ); + LogDebug("Sync handle : " << handle); + if (event->opId && event->m_messagingService) + { + event->m_messagingService->setHandleToOpId(event->opId, handle); + } + } + else + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::InvalidArgumentException); + } + else + { + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::InvalidArgumentException); + } + } + else + { + LogDebug(" cancel. "); + event->setCancelAllowed(true); + } + } + + } + else if (MessagingServiceEventType == EventMessagingService::MESSAGING_SERVICE_EVENT_TYPE_SYNC_FOLDER) + { + if (event->m_messagingService) + { + if (!event->checkCancelled()) { + int type = event->m_messagingService->getType(); + LogDebug("messaging service type :" << type); + + event->m_messagingService->setRequestReceiver(this); + event->m_messagingService->setMessagingServiceEvent(event); // + + if (type == Api::Messaging::EMAIL) + { + event->switchToManualAnswer(); //switch to manual answer; + LogDebug("privateData->getAccountId() :" << event->m_messagingService->getAccountID()); + + if ( event->m_messagingService->getAccountID() > 0) + { + int handle = event->m_messagingService->syncFolder( event->m_messagingService, event->m_folder_name, event->m_sync_limit); + LogDebug("Sync Folder handle : " << handle); + if (event->opId && event->m_messagingService) + { + event->m_messagingService->setHandleToOpId(event->opId, handle); + } + } + else + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::InvalidArgumentException); + } + else + { + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::InvalidArgumentException); + } + } + else + { + LogDebug(" cancel. "); + event->setCancelAllowed(true); + } + } + } + else + { + LogDebug(" Cancel "); + event->setCancelAllowed(true); + } + + } + Catch (WrtDeviceApis::Commons::PlatformException) { + MsgLogError("platform exception"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + } + +} + +void ReqReceiverMessage::OnRequestReceived(const EventDeleteConversationsPtr& event) +{ + LogDebug("enter"); + + Try + { + if (event->isFilterUsing()) + { + LogDebug("filter use"); + + //check filter validation + FilterPtr filter = event->getFilter(); + if(filter != NULL) + { + ConversationFilterValidatorPtr validator = + ConversationFilterValidatorFactory::getConversationFilterValidator(); + + + FilterValidatorPtr filterValidator = DPL::StaticPointerCast(validator); + bool isValidFilter = filter->validate(filterValidator); + + if(isValidFilter == false) + { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + } + + if (IMessaging::getInstance().deleteConversations(event->getSortMode(), event->getFilter()) == false) + { + Throw(WrtDeviceApis::Commons::PlatformException); + } + //.queryConversations(event->getSortMode(), event->getFilter()); + } + else + { + LogDebug("no filter"); + + if (IMessaging::getInstance().deleteConversations(event->getConversations()) == false) + { + Throw(WrtDeviceApis::Commons::PlatformException); + } + } + } + Catch(WrtDeviceApis::Commons::PlatformException) + { + MsgLogError("platform exception"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) + { + MsgLogError("InvalidArgumentException"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::InvalidArgumentException); + } +} + +void ReqReceiverMessage::OnRequestReceived(const EventQueryFoldersPtr& event) +{ + LogDebug("enter"); + + Try + { + + //check filter validation + Tizen::FilterPtr filter = event->getFilter(); + if(filter != NULL){ + FolderFilterValidatorPtr validator = + FolderFilterValidatorFactory::getFolderFilterValidator(); + + FilterValidatorPtr filterValidator = DPL::StaticPointerCast(validator); + + bool isValidFilter = filter->validate(filterValidator); + if(isValidFilter == false){ + MsgLogError("[ERROR]Filter is Invalid"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + } + + vector tmp = IMessaging::getInstance().queryFolders(event->getFilter()); + event->addFolders(tmp); + } + Catch(WrtDeviceApis::Commons::PlatformException) + { + MsgLogError("platform exception"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) + { + MsgLogError("InvalidArgumentException"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::InvalidArgumentException); + } +} + +} +} +} diff --git a/src/platform/API/Messaging/ReqReceiverMessage.h b/src/platform/API/Messaging/ReqReceiverMessage.h new file mode 100755 index 0000000..e6a9fcf --- /dev/null +++ b/src/platform/API/Messaging/ReqReceiverMessage.h @@ -0,0 +1,148 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file ReqReceiverMessage.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef REQRECEIVERMESSAGE_H +#define REQRECEIVERMESSAGE_H + +#include + +#include "EventSendMessage.h" +#include "EventUpdateMessage.h" +#include "EventDeleteMessage.h" +#include "EventDeleteMessages.h" +#include "EventUpdateMessages.h" +#include "EventQueryMessages.h" +#include "EventGetConversationId.h" +#include "EventQueryConversations.h" +#include "EventQueryFolders.h" +#include "EventDeleteConversations.h" +#include "EventMessagingService.h" + +#include "log.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +typedef WrtDeviceApis::Commons::EventRequestReceiver +EventSendMessageReqReceiver; +typedef WrtDeviceApis::Commons::EventRequestReceiver +EventUpdateMessageReqReceiver; +typedef WrtDeviceApis::Commons::EventRequestReceiver +EventDeleteMessageReqReceiver; +typedef WrtDeviceApis::Commons::EventRequestReceiver +EventDeleteMessagesReqReceiver; +typedef WrtDeviceApis::Commons::EventRequestReceiver +EventUpdateMessagesReqReceiver; +typedef WrtDeviceApis::Commons::EventRequestReceiver +EventQueryMessagesReqReceiver; +typedef WrtDeviceApis::Commons::EventRequestReceiver +EventGetConversationIdReqReceiver; +typedef WrtDeviceApis::Commons::EventRequestReceiver +EventQueryConversationsReqReceiver; +typedef WrtDeviceApis::Commons::EventRequestReceiver +EventDeleteConversationsReqReceiver; +typedef WrtDeviceApis::Commons::EventRequestReceiver +EventQueryFoldersReqReceiver; +typedef WrtDeviceApis::Commons::EventRequestReceiver +EventMessagingServiceReqReceiver; +class ReqReceiverMessage : public EventSendMessageReqReceiver, + public EventUpdateMessageReqReceiver, + public EventDeleteMessageReqReceiver, + public EventDeleteMessagesReqReceiver, + public EventUpdateMessagesReqReceiver, + public EventQueryMessagesReqReceiver, + public EventGetConversationIdReqReceiver, + public EventQueryConversationsReqReceiver, + public EventDeleteConversationsReqReceiver, + public EventQueryFoldersReqReceiver, + public EventMessagingServiceReqReceiver +{ + private: + bool validateFilter(const Tizen::FilterPtr& filter); + + public: + ReqReceiverMessage(); + + virtual ~ReqReceiverMessage(); + + void sendMessage(const EventSendMessagePtr& event); + + void updateMessage(const EventUpdateMessagePtr& event); + + void deleteMessage(const EventDeleteMessagePtr& event); + + void deleteMessages(const EventDeleteMessagesPtr& event); + + void updateMessages(const EventUpdateMessagesPtr& event); + + void queryMessages(const EventQueryMessagesPtr& event); + + void getConversationId(const EventGetConversationIdPtr& event); + + void queryConversations(const EventQueryConversationsPtr& event); + + void deleteConversations(const EventDeleteConversationsPtr& event); + + void queryFolders(const EventQueryFoldersPtr& event); + + void loadMessageBody(const EventMessagingServicePtr& event); + + void loadMessageAttachment(const EventMessagingServicePtr& event); + + void sync(const EventMessagingServicePtr& event); + + void syncFolder(const EventMessagingServicePtr& event); + + + protected: + void OnRequestReceived(const EventSendMessagePtr& event); + + void OnRequestReceived(const EventUpdateMessagePtr& event); + + void OnRequestReceived(const EventDeleteMessagePtr& event); + + void OnRequestReceived(const EventDeleteMessagesPtr& event); + + void OnRequestReceived(const EventUpdateMessagesPtr& event); + + void OnRequestReceived(const EventQueryMessagesPtr& event); + + void OnRequestReceived(const EventGetConversationIdPtr& event); + + void OnRequestReceived(const EventQueryConversationsPtr& event); + + void OnRequestReceived(const EventDeleteConversationsPtr& event); + + void OnRequestReceived(const EventQueryFoldersPtr& event); + + void OnRequestReceived(const EventMessagingServicePtr& event); +}; + +typedef DPL::Singleton ReqReceiverMessageSingleton; +} +} +} +#endif // REQRECEIVERMESSAGE_H diff --git a/src/platform/API/Messaging/SourceAddress.cpp b/src/platform/API/Messaging/SourceAddress.cpp new file mode 100755 index 0000000..a646d65 --- /dev/null +++ b/src/platform/API/Messaging/SourceAddress.cpp @@ -0,0 +1,78 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file SourceAddress.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include "Commons/Exception.h" +#include "SourceAddress.h" + +using namespace std; +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +SourceAddress::SourceAddress() : + m_validSourceAddress(false) +{ +} + +SourceAddress::~SourceAddress() +{ +} + +void SourceAddress::setSourceAddressValidity(bool state) +{ + m_validSourceAddress = state; +} + +bool SourceAddress::getSourceAddressValidity() const +{ + return m_validSourceAddress; +} + +std::string SourceAddress::getSourceAddress() const +{ + return m_sourceAddress; +} + +void SourceAddress::setSourceAddress(const Recipients& value) +{ + if (value.getRecipientSize() != 1) { + LogError("wrong source address value"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + m_sourceAddress = value.getRecipient(0); + m_validSourceAddress = false; +} + +void SourceAddress::setSourceAddress(const std::string& value) +{ + m_sourceAddress = value; + m_validSourceAddress = false; +} +} +} +} diff --git a/src/platform/API/Messaging/SourceAddress.h b/src/platform/API/Messaging/SourceAddress.h new file mode 100755 index 0000000..47973e1 --- /dev/null +++ b/src/platform/API/Messaging/SourceAddress.h @@ -0,0 +1,65 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file SourceAddress.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef SOURCEADDRESS_H +#define SOURCEADDRESS_H + +#include "Recipient.h" +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class SourceAddress +{ + private: // fields + + std::string m_sourceAddress; + + bool m_validSourceAddress; + + public: + + SourceAddress(); + + virtual ~SourceAddress(); + + void setSourceAddressValidity(bool state); + + bool getSourceAddressValidity() const; + + std::string getSourceAddress() const; + + void setSourceAddress(const Recipients& value); + + void setSourceAddress(const std::string& value); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/StorageChangesConversationFilterValidator.cpp b/src/platform/API/Messaging/StorageChangesConversationFilterValidator.cpp new file mode 100755 index 0000000..569d145 --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesConversationFilterValidator.cpp @@ -0,0 +1,68 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesConversationFilterValidator.cpp + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#include "StorageChangesConversationFilterValidator.h" +#include "StorageChangesConversationFilterValidatorFactory.h" + +#include + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + StorageChangesConversationFilterValidator::StorageChangesConversationFilterValidator(PropertyStructArray properties, + MatchFlagStrArray matchFlag,Api::Tizen::PrimitiveType idType):FilterValidator(properties, matchFlag){ + m_isTypeSetted = false; + } + + StorageChangesConversationFilterValidator::~StorageChangesConversationFilterValidator(){ + } + + bool StorageChangesConversationFilterValidator::validateAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue){ + bool retVal = false; + if(attrName.compare(StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_TIMESTAMP)!=0){ + LogError(">>> [ERROR] Not Supported attribute :[" << attrName << "]"); + return false; + } + + retVal = FilterValidator::validateAttributeRange(attrName, initialValue, endValue); + return retVal; + } + + bool StorageChangesConversationFilterValidator::validateAttribute(std::string& attrName, Api::Tizen::AnyArrayPtr& values, + std::string& matchFlag, bool caseSensitive, int depth){ + + bool retBool = false; + + retBool = FilterValidator::validateAttribute(attrName, values, matchFlag, caseSensitive, depth); + LogDebug(">>> retBool:" << retBool); + return retBool; + } + + } + } + +} diff --git a/src/platform/API/Messaging/StorageChangesConversationFilterValidator.h b/src/platform/API/Messaging/StorageChangesConversationFilterValidator.h new file mode 100755 index 0000000..5448e34 --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesConversationFilterValidator.h @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesConversationFilterValidator.h + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#ifndef STORAGECHANGESCONVERSATIONATOR_H_ +#define STORAGECHANGESCONVERSATIONATOR_H_ + +#include + + +namespace TizenApis { + + namespace Platform { + + namespace Messaging { + + class StorageChangesConversationFilterValidator: public Api::Tizen::FilterValidator { + private: + bool m_isTypeSetted; + + public: + StorageChangesConversationFilterValidator(Api::Tizen::PropertyStructArray properties, + Api::Tizen::MatchFlagStrArray matchFlag,Api::Tizen::PrimitiveType idType); + + virtual ~StorageChangesConversationFilterValidator(); + + // validate AttributeRangeFilter + virtual bool validateAttributeRange(std::string& attrName, + Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue); + + virtual bool validateAttribute(std::string& attrName, Api::Tizen::AnyArrayPtr& values, + std::string& matchFlag, bool caseSensitive, int depth=0); + + + + }; + + typedef DPL::SharedPtr StorageChangesConversationFilterValidatorPtr; + } +} + } + +#endif diff --git a/src/platform/API/Messaging/StorageChangesConversationFilterValidatorFactory.cpp b/src/platform/API/Messaging/StorageChangesConversationFilterValidatorFactory.cpp new file mode 100755 index 0000000..f0ef126 --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesConversationFilterValidatorFactory.cpp @@ -0,0 +1,79 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesConversationFilterValidatorFactory.cpp + * + * Created on: 2011. 10. 27. + * Author: sangtai + */ + +#include "StorageChangesConversationFilterValidatorFactory.h" + +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + const std::string StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_TYPE = "type"; + const std::string StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_TIMESTAMP = "timestamp"; + const std::string StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_MESSAGE_COUNT = "messageCount"; + const std::string StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_UNREAD_MESSAGES = "unreadMessages"; + const std::string StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_PREVIEW = "preview"; + const std::string StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_IS_READ = "read"; + const std::string StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_FROM = "from"; + const std::string StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_TO = "to"; + const std::string StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_CC = "cc"; + const std::string StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_BCC = "bcc"; + const std::string StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_SUBJECT = "subject"; + const std::string StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_LAST_MESSAGE_ID = "lastMessageId"; + + static PropertyStructArray properties = + { + {"type", Api::Tizen::PrimitiveType_String}, + {StorageChangesConversationFilterValidatorFactory::ATTRIBUTE_TIMESTAMP.c_str(), Api::Tizen::PrimitiveType_Time}, + {"messageCount", Api::Tizen::PrimitiveType_Number}, + {"unreadMessages", Api::Tizen::PrimitiveType_Number}, + {"preview", Api::Tizen::PrimitiveType_String}, + {"read", Api::Tizen::PrimitiveType_Number}, + {"from", Api::Tizen::PrimitiveType_String}, + {"to", Api::Tizen::PrimitiveType_String}, + {"cc", Api::Tizen::PrimitiveType_String}, + {"bcc", Api::Tizen::PrimitiveType_String}, + {"subject", Api::Tizen::PrimitiveType_String}, + {"lastMessageId", Api::Tizen::PrimitiveType_String}, + {0, Api::Tizen::PrimitiveType_Notype} + }; + + static MatchFlagStrArray matchFlag{ + "EXACTLY", + "CONTAINS", + "STARTSWITH", + "ENDSWITH", + 0 + }; + + StorageChangesConversationFilterValidatorPtr StorageChangesConversationFilterValidatorFactory::getStorageChangesConversationFilterValidator() + { + static StorageChangesConversationFilterValidatorPtr theInstance = + StorageChangesConversationFilterValidatorPtr(new StorageChangesConversationFilterValidator(properties, matchFlag, Api::Tizen::PrimitiveType_Int)); + + return theInstance; + } + + } + } //naspace Platform +} //naspace WrtPlugins diff --git a/src/platform/API/Messaging/StorageChangesConversationFilterValidatorFactory.h b/src/platform/API/Messaging/StorageChangesConversationFilterValidatorFactory.h new file mode 100755 index 0000000..81167cd --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesConversationFilterValidatorFactory.h @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesConversationFilterValidatorFactory.h + * + * Created on: 2011. 10. 27. + * Author: sangtai + */ + +#ifndef STORAGECHANGESCONVERSATIONFILTERVALIDATORFACTORY_H_ +#define STORAGECHANGESCONVERSATIONFILTERVALIDATORFACTORY_H_ + +#include +#include "StorageChangesConversationFilterValidator.h" + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + class StorageChangesConversationFilterValidatorFactory { + private: + StorageChangesConversationFilterValidatorFactory() + { + } + + public: + static StorageChangesConversationFilterValidatorPtr getStorageChangesConversationFilterValidator(); + + public: + static const std::string ATTRIBUTE_TYPE; + static const std::string ATTRIBUTE_TIMESTAMP; + static const std::string ATTRIBUTE_MESSAGE_COUNT; + static const std::string ATTRIBUTE_UNREAD_MESSAGES; + static const std::string ATTRIBUTE_PREVIEW; + static const std::string ATTRIBUTE_IS_READ; + static const std::string ATTRIBUTE_FROM; + static const std::string ATTRIBUTE_TO; + static const std::string ATTRIBUTE_CC; + static const std::string ATTRIBUTE_BCC; + static const std::string ATTRIBUTE_SUBJECT; + static const std::string ATTRIBUTE_LAST_MESSAGE_ID; + }; + + } + } //Platform +} + +#endif /* MESSAGINGFILTERVALIDATORFACTORY_H_ */ diff --git a/src/platform/API/Messaging/StorageChangesConversationGenerator.cpp b/src/platform/API/Messaging/StorageChangesConversationGenerator.cpp new file mode 100755 index 0000000..e869da9 --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesConversationGenerator.cpp @@ -0,0 +1,576 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesConversationGenerator.cpp + * + * Created on: 2011. 10. 28. + * Author: sangtai + */ + +#include "StorageChangesConversationGenerator.h" +#include "StorageChangesConversationFilterValidatorFactory.h" +#include "API/Messaging/ConversationFilterValidatorFactory.h" + +#include "IMessagingTypes.h" + +#include + +#include + +using namespace std; +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + + const std::string StorageChangesConversationGenerator::STRING_MATCH_EXCACTLY = "EXACTLY"; + const std::string StorageChangesConversationGenerator::STRING_MATCH_CONTAINS = "CONTAINS"; + const std::string StorageChangesConversationGenerator::STRING_MATCH_STARTSWITH = "STARTSWITH"; + const std::string StorageChangesConversationGenerator::STRING_MATCH_ENDSWITH = "ENDSWITH"; +// const std::string StorageChangesConversationGenerator::STRING_MATCH_CASESENSITIVE = "CASESENSITIVE"; + + const int StorageChangesConversationGenerator::MESSAGE_TYPE_NOT_INITIALIZED = -1; + + StorageChangesConversationGenerator::StorageChangesConversationGenerator(Api::Messaging::IConversationPtr conv):m_messageType(MESSAGE_TYPE_NOT_INITIALIZED) { + + m_type = conv->getType(); + m_time = conv->getTime(); + m_messageCount = conv->getMessageCount(); + m_unreadMessages = conv->getUnreadMessages(); + m_preview = conv->getPreview(); + m_read = conv->getRead(); + m_from = conv->getFrom(); + m_subject = conv->getSubject(); + m_to = conv->getTo(); + m_cc = conv->getCC(); + m_bcc = conv->getBCC(); + m_lastMessageId = conv->getLastMessageId(); + + struct tm * timeinfo; + timeinfo = localtime( &m_time ); + + } + + StorageChangesConversationGenerator::~StorageChangesConversationGenerator() { + } + + + void StorageChangesConversationGenerator::visitPreComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + m_operand.push_back(leftblank); + LogDebug("Left_blank"); + LogDebug(">>>"); + } + + void StorageChangesConversationGenerator::visitInComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + if(type == UNION_FILTER ){ + LogDebug("UNION_FILTER"); + m_operand.push_back(operandUnion); + }else if(type == INTERSECTION_FILTER){ + LogDebug("INTERSECTION_FILTER"); + m_operand.push_back(operandIntersection); + }else{ + LogError("[ERROR] invalid Filter type:" << type); + } + + LogDebug(">>>"); + } + + void StorageChangesConversationGenerator::visitPostComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + bool data1, data2; + do + { + LogDebug("m_result size =" << m_result.size()); + data1 = m_result.back(); + m_result.pop_back(); + data2 = m_result.back(); + m_result.pop_back(); + LogDebug("m_result size =" << m_result.size()); + LogDebug("m_operand.back() =" << m_operand.back()); + LogDebug("m_operand size =" << m_operand.size()); + if(m_operand.back() == operandUnion) + { + LogDebug("Union"); + LogDebug("data1 = " << data1); + LogDebug("data2 = " << data2); + LogDebug("data1 || data2 = " << (data1 || data2)); + m_operand.pop_back(); + m_result.push_back(data1 || data2); + LogDebug("result" << m_result.back()); + LogDebug("m_result size =" << m_result.size()); + } + else if(m_operand.back() == operandIntersection) + { + LogDebug("Intersection"); + LogDebug("data1 = " << data1); + LogDebug("data2 = " << data2); + LogDebug("data1 && data2 = " << (data1 && data2)); + m_operand.pop_back(); + m_result.push_back(data1 && data2); + LogDebug("result " << m_result.back()); + LogDebug("m_result size =" << m_result.size()); + + } + }while(m_operand.back() != leftblank); + m_operand.pop_back(); + LogDebug("elase leftblank from m_operand"); + LogDebug("m_operand size =" << m_operand.size()); + LogDebug(">>>"); + } + + struct tm StorageChangesConversationGenerator::convertToTimeFormat(const std::string& timeString){ + LogDebug("<<< timeString:[" << timeString << "]"); + + struct tm tm_Time; + + int nextStart = 0; + + int yearLength = 4; + tm_Time.tm_year = atoi(timeString.substr(0, yearLength).c_str())-1900; + nextStart = nextStart + yearLength; + LogDebug("<<< tm_Time.tm_year:[" << tm_Time.tm_year << "]"); + + int monthLength = 2; + tm_Time.tm_mon = atoi(timeString.substr(nextStart, monthLength).c_str()); + nextStart = nextStart + monthLength; + LogDebug("<<< initTime.tm_mon:[" << tm_Time.tm_mon << "]"); + + int dateLength = 2; + tm_Time.tm_mday = atoi(timeString.substr(nextStart, dateLength).c_str()); + nextStart = nextStart + dateLength; + LogDebug("<<< initTime.tm_mday:[" << tm_Time.tm_mday << "]"); + + int hourLength = 2; + tm_Time.tm_hour = atoi(timeString.substr(nextStart, hourLength).c_str()); + nextStart = nextStart + hourLength; + LogDebug("<<< initTime.tm_hour:[" << tm_Time.tm_hour << "]"); + + int minuteLength = 2; + tm_Time.tm_min = atoi(timeString.substr(nextStart, minuteLength).c_str()); + nextStart = nextStart + minuteLength; + LogDebug("<<< initTime.tm_min:[" << tm_Time.tm_min << "]"); + + int secondLength = 2; + tm_Time.tm_sec = atoi(timeString.substr(nextStart, secondLength).c_str()); + LogDebug("<<< initTime.tm_sec:[" << tm_Time.tm_sec << "]"); + + return tm_Time; + } + + bool StorageChangesConversationGenerator::getMatchExactlyClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string valueString = value->toString(); + LogDebug("<<< attrName : " << attrName); + LogDebug("<<< valueString : " << valueString); + LogDebug("<<< attrName.compare(valueString) : " << attrName.compare(valueString)); + + if(attrName.compare(valueString) == 0) + { + LogDebug("<<< getMatchExactlyClause SAME >>>"); + return TRUE; + } + else{ + LogDebug("<<< getMatchExactlyClause DIFF >>>"); + return FALSE; + } + } + + bool StorageChangesConversationGenerator::getMatchContainsClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string valueString = value->toString(); + LogDebug("<<< attrName : " << attrName); + LogDebug("<<< valueString : " << valueString); + LogDebug("<<< attrName.find(valueString) : " << attrName.find(valueString)); + + if(attrName.find(valueString) != std::string::npos) + { + LogDebug("<<< getMatchContainsClause CONTAINS >>>"); + return TRUE; + }else{ + LogDebug("<<< getMatchContainsClause NOT CONTAINS >>>"); + return FALSE; + } + } + + bool StorageChangesConversationGenerator::getMatchStartwithClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string valueString = value->toString(); + LogDebug("<<< attrName : " << attrName); + LogDebug("<<< valueString : " << valueString); + LogDebug("<<< attrName.compare(0,valueString.size(), valueString) : " << attrName.compare(0,valueString.size(), valueString)); + + + if(attrName.size()-valueString.size() < 0) + return FALSE; + + if(attrName.compare(0,valueString.size(), valueString) == 0) + { + LogDebug("<<< getMatchStartwithClause START WITH >>>"); + return TRUE; + } + else{ + LogDebug("<<< getMatchStartwithClause NOT START WITH >>>"); + return FALSE; + } + } + + bool StorageChangesConversationGenerator::getMatchEndwithClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string valueString = value->toString(); + + LogDebug("<<< attrName : " << attrName); + LogDebug("<<< valueString : " << valueString); + LogDebug("<<< attrName.compare(attrName.size()-valueString.size(),valueString.size(), valueString) : " << attrName.compare(attrName.size()-valueString.size(),valueString.size(), valueString)); + + + if(attrName.size()-valueString.size() < 0) + return FALSE; + + if(attrName.compare(attrName.size()-valueString.size(),valueString.size(), valueString) == 0 ) + { + LogDebug("<<< getMatchEndwithClause END WITH >>>"); + return TRUE; + } + else{ + LogDebug("<<< getMatchEndwithClause NOT END WITH >>>"); + return FALSE; + } + } + + void StorageChangesConversationGenerator::visitAttribute(std::string& attrName, + AnyArrayPtr& values, std::string& matchFlag, bool caseSensitive, int depth){ + LogDebug("<<< attrName:[" << attrName << "], matchFlag:[" << matchFlag << "]"); + LogDebug("values->size():" << values->size()); + + Api::Tizen::FilterType filterType = UNION_FILTER; + + if(matchFlag.compare("EXIST")==0){ + //TODO implement for EXIST + }else if(values->size() == 1){ + AnyPtr matchValue = values->at(0); + visitAttributeEach(attrName, matchValue, matchFlag, depth); + }else{ + visitPreComposite(filterType, depth); + + AnyArray::iterator iter; + for(iter=values->begin(); iter!= values->end(); iter++){ + + if(iter != values->begin()){ + + visitInComposite(filterType, depth); + } + + AnyPtr matchValue = *iter; + visitAttributeEach(attrName, matchValue, matchFlag, depth); + } + + visitPostComposite(filterType, depth); + } + LogDebug(">>>"); + } + + void StorageChangesConversationGenerator::visitAttributeEach(std::string& attrName, Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth){ + LogDebug("<<< attrName:[" << attrName << "], value:[" << value->toString() << "]"); + std::string valueString; + +// Check msg_type and filter_type + if(attrName.compare("type")==0){ + LogDebug("<<< value:[" << value << "]"); + std::string convertType = value->toString(); + int nType = convertMessageType(convertType); + if((int)m_type == nType) + { + m_result.push_back(TRUE); + LogDebug("<<< type is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< type is different"); + } + return; + } + if(attrName.compare("messageCount")==0){ + LogDebug("<<< value:[" << value << "]"); + int nType = atoi(value->toString().c_str()); + if((int)m_messageCount == nType) + { + m_result.push_back(TRUE); + LogDebug("<<< messageCount is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< messageCount is different"); + } + return; + } + if(attrName.compare("unreadMessages")==0){ + LogDebug("<<< value:[" << value << "]"); + int nType = atoi(value->toString().c_str()); + if((int)m_unreadMessages == nType) + { + m_result.push_back(TRUE); + LogDebug("<<< unreadMessages is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< unreadMessages is different"); + } + return; + } + if(attrName.compare("read")==0){ + LogDebug("<<< value:[" << value << "]"); + int nType = value->toString().compare("true"); + if((int)m_read == nType) + { + m_result.push_back(TRUE); + LogDebug("<<< read is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< read is different"); + } + return; + } + if(attrName.compare("lastMessageId")==0){ + LogDebug("<<< value:[" << value << "]"); + int nType = atoi(value->toString().c_str()); + if((int)m_lastMessageId == nType) + { + m_result.push_back(TRUE); + LogDebug("<<< lastMessageId is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< lastMessageId is different"); + } + return; + } + + if(attrName.compare("preview")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_body:[" << m_preview << "]"); + + valueString = m_preview; + if(getMatchFlagResult(value, valueString, matchFlag)) + { + m_result.push_back(TRUE); + LogDebug("<<< preview is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< preview is different"); + } + return; + } + if(attrName.compare("from")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_from:[" << m_from << "]"); + + valueString = m_from; + if(getMatchFlagResult(value, valueString, matchFlag)) + { + m_result.push_back(TRUE); + LogDebug("<<< from is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< from is different"); + } + return; + } + if(attrName.compare("subject")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_subject:[" << m_subject << "]"); + + valueString = m_subject; + if(getMatchFlagResult(value, valueString, matchFlag)) + { + m_result.push_back(TRUE); + LogDebug("<<< subject is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< subject is different"); + } + return; + } + + if(attrName.compare("to")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_to.size :[" << m_to.size() << "]"); + + bool result = FALSE; + for(unsigned int i=0; i < m_to.size(); i++) + { + valueString = m_to[i]; + result = result || getMatchFlagResult(value, valueString, matchFlag); + } + LogDebug("<<< to compare result is :" << result); + m_result.push_back(result); + return; + } + + if(attrName.compare("cc")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_cc.size :[" << m_cc.size() << "]"); + + bool result = FALSE; + for(unsigned int i=0; i < m_cc.size(); i++) + { + valueString = m_cc[i]; + result = result || getMatchFlagResult(value, valueString, matchFlag); + } + LogDebug("<<< cc compare result is : " << result); + m_result.push_back(result); + return; + } + + if(attrName.compare("bcc")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_cc.size :[" << m_bcc.size() << "]"); + + bool result = FALSE; + for(unsigned int i=0; i < m_bcc.size(); i++) + { + valueString = m_bcc[i]; + result = result || getMatchFlagResult(value, valueString, matchFlag); + } + LogDebug("<<< bcc compare result is : " << result); + m_result.push_back(result); + return; + } + + LogDebug(">>>"); + } + + int StorageChangesConversationGenerator::convertMessageType(std::string& stringType){ + LogDebug("<<< stringType:[" << stringType << "]"); + + int retMessageType = -1; + + if(stringType.compare("SMS") ==0){ + retMessageType = Api::Messaging::SMS; + }else if(stringType.compare("MMS") ==0){ + retMessageType = Api::Messaging::MMS; + }else if(stringType.compare("EMAIL") ==0){ + retMessageType = Api::Messaging::EMAIL; + }else{ + LogError("invalid type:[" << stringType << "]"); + return -1; + } + + LogDebug(">>> retMessageType:" << retMessageType); + return retMessageType; + } + + std::string StorageChangesConversationGenerator::convertBooleanStringToIntegerString(std::string& booleanString){ + std::string retString; + + if(booleanString.compare("true") == 0){ + retString = "1"; + }else if(booleanString.compare("false") == 0){ + retString = "0"; + }else{ + LogError("invalid booleanString:[" << booleanString << "]"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "invalid booleanString :[" + booleanString + "]"); + } + return retString; + } + + void StorageChangesConversationGenerator::visitAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth) { + time_t init_time, mid_time, end_time; + struct tm retValue; + + if(attrName.compare("timestamp")==0){ + retValue = convertToTimeFormat(initialValue->toString()); + init_time = mktime(&retValue); + + mid_time = m_time; + + retValue = convertToTimeFormat(endValue->toString()); + end_time = mktime(&retValue); + + LogDebug("<<< mktime(initialValue):[" << init_time << "]"); + LogDebug("<<< mktime(m_dateTime):[" << mid_time << "]"); + LogDebug("<<< mktime(endValue):[" << end_time << "]"); + LogDebug("<<< mid_time - init_time:[" << mid_time - init_time << "]"); + LogDebug("<<< end_time - mid_time:[" << end_time - mid_time << "]"); + + if(((mid_time - init_time) >= 0 ) && ((end_time - mid_time) >= 0 )) + { + LogDebug("<<< timestamp is in range"); + m_result.push_back(TRUE); + } + else + { + LogDebug("<<< timestamp is out of range"); + m_result.push_back(FALSE); + } + } + } + + bool StorageChangesConversationGenerator::getMatchFlagResult(Api::Tizen::AnyPtr& value, std::string& valueString, std::string& matchFlag) + { + std::vector::iterator iter; + bool result = FALSE; + if(matchFlag.compare(STRING_MATCH_EXCACTLY) == 0){ + LogDebug("STRING_MATCH_EXCACTLY"); + result = result || getMatchExactlyClause(valueString, value); + }else if(matchFlag.compare(STRING_MATCH_CONTAINS) == 0){ + LogDebug("STRING_MATCH_CONTAINS"); + result = result || getMatchContainsClause(valueString, value); + }else if(matchFlag.compare(STRING_MATCH_STARTSWITH) == 0){ + LogDebug("STRING_MATCH_STARTSWITH"); + result = result || getMatchStartwithClause(valueString, value); + }else if(matchFlag.compare(STRING_MATCH_ENDSWITH) == 0){ + LogDebug("STRING_MATCH_ENDSWITH"); + result = result || getMatchEndwithClause(valueString, value); + }else{ + LogDebug("[ERROR]invalid match flag : iter:" << *iter); + } + return result; + } + + bool StorageChangesConversationGenerator::getCompareResult() + { + bool result; + LogDebug("m_result.size() " << m_result.size()); + result = m_result.back(); + m_result.pop_back(); + LogDebug("result = " << result); + return result; + } +} + } //namespace Platform +} //namespace WrtPlugins diff --git a/src/platform/API/Messaging/StorageChangesConversationGenerator.h b/src/platform/API/Messaging/StorageChangesConversationGenerator.h new file mode 100755 index 0000000..09ac05d --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesConversationGenerator.h @@ -0,0 +1,121 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesConversationGenerator.h + * + * Created on: 2011. 10. 28. + * Author: sangtai + */ + +#ifndef STORAGECHANGESCONVERSATIONGENERATOR_H_ +#define STORAGECHANGESCONVERSATIONGENERATOR_H_ + +#include +#include +#include + +#include + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + +// using namespace std; + + class StorageChangesConversationGenerator: public TizenApis::Api::Tizen::IFilterVisitor{ + public: + + enum operandType + { + leftblank = 1, + rightblank = 2, + operandUnion = 3, + operandIntersection = 4 + }; + + StorageChangesConversationGenerator(Api::Messaging::IConversationPtr conv); + virtual ~StorageChangesConversationGenerator(); + + void visitPreComposite(Api::Tizen::FilterType& type, int depth); + void visitInComposite(Api::Tizen::FilterType& type, int depth); + void visitPostComposite(Api::Tizen::FilterType& type, int depth); + void visitAttribute(std::string& attrName, + Api::Tizen::AnyArrayPtr& values, std::string& matchFlag, bool caseSensitive, int depth); + + void visitAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth); + + bool getMatchFlagResult(Api::Tizen::AnyPtr& value, std::string& valueString, std::string& matchFlag); + bool getCompareResult(); + + private: + bool getMatchExactlyClause(std::string& attrName, Api::Tizen::AnyPtr& value); + bool getMatchContainsClause(std::string& attrName, Api::Tizen::AnyPtr& value); + bool getMatchStartwithClause(std::string& attrName, Api::Tizen::AnyPtr& value); + bool getMatchEndwithClause(std::string& attrName, Api::Tizen::AnyPtr& value); + bool getBetweenRangeClause(struct tm initialValue, struct tm endValue); + + void visitAttributeEach(std::string& attrName, Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth); + int convertMessageType(std::string& stringType); + std::string convertBooleanStringToIntegerString(std::string& booleanString); + + struct tm convertToTimeFormat(const std::string& timeString); + std::string createTimeString(std::string& timeString); + std::string createFolderType(std::string& value); + std::string createPriorityType(std::string& value); + std::string createDateTimeType(Api::Tizen::AnyPtr& value); + + private: + int m_messageType; + + std::vector typeVector; + std::map attributeMap; + + std::vector m_result; + std::vector m_operand; + +// unsigned int m_Id; + unsigned short int m_type; + time_t m_time; + unsigned long m_messageCount; + unsigned long m_unreadMessages; + std::string m_preview; + bool m_read; + std::string m_from; + std::string m_subject; + std::vector m_to; + std::vector m_cc; + std::vector m_bcc; + unsigned int m_lastMessageId; + + Api::Messaging::RecipientsPtr Recipents; + std::string m_currentType; + + static const std::string STRING_MATCH_EXCACTLY; + static const std::string STRING_MATCH_CONTAINS; + static const std::string STRING_MATCH_STARTSWITH; + static const std::string STRING_MATCH_ENDSWITH; + static const std::string STRING_MATCH_CASESENSITIVE; + + static const int MESSAGE_TYPE_NOT_INITIALIZED; + + }; + + typedef DPL::SharedPtr StorageChangesConversationGeneratorPtr; + } // namespace Platform +} // namespace WrtPlugins +} +#endif /* MESSAGEQUERYGENERATOR_H_ */ diff --git a/src/platform/API/Messaging/StorageChangesFolderFilterValidator.cpp b/src/platform/API/Messaging/StorageChangesFolderFilterValidator.cpp new file mode 100755 index 0000000..c9338b3 --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesFolderFilterValidator.cpp @@ -0,0 +1,63 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesFolderFilterValidator.cpp + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#include "StorageChangesFolderFilterValidator.h" +#include "StorageChangesFolderFilterValidatorFactory.h" + +#include + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + StorageChangesFolderFilterValidator::StorageChangesFolderFilterValidator(PropertyStructArray properties, + MatchFlagStrArray matchFlag,Api::Tizen::PrimitiveType idType):FilterValidator(properties, matchFlag){ + m_isTypeSetted = false; + } + + StorageChangesFolderFilterValidator::~StorageChangesFolderFilterValidator(){ + } + + bool StorageChangesFolderFilterValidator::validateAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue){ + bool retVal = false; + LogError(">>> [ERROR] Not Supported attribute :[" << attrName << "]"); + return retVal; + } + + bool StorageChangesFolderFilterValidator::validateAttribute(std::string& attrName, Api::Tizen::AnyArrayPtr& values, + std::string& matchFlag, bool caseSensitive, int depth){ + + bool retBool = false; + + retBool = FilterValidator::validateAttribute(attrName, values, matchFlag, caseSensitive, depth); + LogDebug(">>> retBool:" << retBool); + return retBool; + + } + } + } + +} diff --git a/src/platform/API/Messaging/StorageChangesFolderFilterValidator.h b/src/platform/API/Messaging/StorageChangesFolderFilterValidator.h new file mode 100755 index 0000000..25f83f6 --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesFolderFilterValidator.h @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesFolderFilterValidator.h + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#ifndef STORAGECHANGESFOLDERATOR_H_ +#define STORAGECHANGESFOLDERATOR_H_ + +#include + + +namespace TizenApis { + + namespace Platform { + + namespace Messaging { + + class StorageChangesFolderFilterValidator: public Api::Tizen::FilterValidator { + private: + bool m_isTypeSetted; + + public: + StorageChangesFolderFilterValidator(Api::Tizen::PropertyStructArray properties, + Api::Tizen::MatchFlagStrArray matchFlag,Api::Tizen::PrimitiveType idType); + + virtual ~StorageChangesFolderFilterValidator(); + + // validate AttributeRangeFilter + virtual bool validateAttributeRange(std::string& attrName, + Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue); + + virtual bool validateAttribute(std::string& attrName, Api::Tizen::AnyArrayPtr& values, + std::string& matchFlag, bool caseSensitive, int depth=0); + + + + }; + + typedef DPL::SharedPtr StorageChangesFolderFilterValidatorPtr; + } +} + } + +#endif diff --git a/src/platform/API/Messaging/StorageChangesFolderFilterValidatorFactory.cpp b/src/platform/API/Messaging/StorageChangesFolderFilterValidatorFactory.cpp new file mode 100755 index 0000000..a30ffc1 --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesFolderFilterValidatorFactory.cpp @@ -0,0 +1,71 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesFolderFilterValidatorFactory.cpp + * + * Created on: 2011. 10. 27. + * Author: sangtai + */ + +#include "StorageChangesFolderFilterValidatorFactory.h" + +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + const std::string StorageChangesFolderFilterValidatorFactory::ATTRIBUTE_ID = "id"; + const std::string StorageChangesFolderFilterValidatorFactory::ATTRIBUTE_PARENT_ID = "parentid"; + const std::string StorageChangesFolderFilterValidatorFactory::ATTRIBUTE_ACCOUNT_ID = "accountid"; + const std::string StorageChangesFolderFilterValidatorFactory::ATTRIBUTE_CONTENT_TYPE = "contentType"; + const std::string StorageChangesFolderFilterValidatorFactory::ATTRIBUTE_NAME = "name"; + const std::string StorageChangesFolderFilterValidatorFactory::ATTRIBUTE_PATH = "path"; + const std::string StorageChangesFolderFilterValidatorFactory::ATTRIBUTE_TYPE = "type"; + const std::string StorageChangesFolderFilterValidatorFactory::ATTRIBUTE_SYNCHRONIZABLE = "synchronizable"; + + static PropertyStructArray properties = + { + {"id", Api::Tizen::PrimitiveType_String}, + {"parentid", Api::Tizen::PrimitiveType_String}, + {"accountid", Api::Tizen::PrimitiveType_String}, + {"contentType", Api::Tizen::PrimitiveType_String}, + {"name", Api::Tizen::PrimitiveType_String}, + {"path", Api::Tizen::PrimitiveType_String}, + {"type", Api::Tizen::PrimitiveType_String}, + {"synchronizable", Api::Tizen::PrimitiveType_Number}, + {0, Api::Tizen::PrimitiveType_Notype} + }; + + static MatchFlagStrArray matchFlag{ + "EXACTLY", + "CONTAINS", + "STARTSWITH", + "ENDSWITH", + 0 + }; + + StorageChangesFolderFilterValidatorPtr StorageChangesFolderFilterValidatorFactory::getStorageChangesFolderFilterValidator() + { + static StorageChangesFolderFilterValidatorPtr theInstance = + StorageChangesFolderFilterValidatorPtr(new StorageChangesFolderFilterValidator(properties, matchFlag, Api::Tizen::PrimitiveType_Int)); + + return theInstance; + } + + } + } //naspace Platform +} //naspace WrtPlugins diff --git a/src/platform/API/Messaging/StorageChangesFolderFilterValidatorFactory.h b/src/platform/API/Messaging/StorageChangesFolderFilterValidatorFactory.h new file mode 100755 index 0000000..bc0c8fb --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesFolderFilterValidatorFactory.h @@ -0,0 +1,57 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesFolderFilterValidatorFactory.h + * + * Created on: 2011. 10. 27. + * Author: sangtai + */ + +#ifndef STORAGECHANGESFOLDERFILTERVALIDATORFACTORY_H_ +#define STORAGECHANGESFOLDERFILTERVALIDATORFACTORY_H_ + +#include +#include "StorageChangesFolderFilterValidator.h" + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + class StorageChangesFolderFilterValidatorFactory { + private: + StorageChangesFolderFilterValidatorFactory() + { + } + + public: + static StorageChangesFolderFilterValidatorPtr getStorageChangesFolderFilterValidator(); + + public: + static const std::string ATTRIBUTE_ID; + static const std::string ATTRIBUTE_PARENT_ID; + static const std::string ATTRIBUTE_ACCOUNT_ID; + static const std::string ATTRIBUTE_CONTENT_TYPE; + static const std::string ATTRIBUTE_NAME; + static const std::string ATTRIBUTE_PATH; + static const std::string ATTRIBUTE_TYPE; + static const std::string ATTRIBUTE_SYNCHRONIZABLE; + }; + + } + } //Platform +} + +#endif /* MESSAGINGFILTERVALIDATORFACTORY_H_ */ diff --git a/src/platform/API/Messaging/StorageChangesFolderGenerator.cpp b/src/platform/API/Messaging/StorageChangesFolderGenerator.cpp new file mode 100755 index 0000000..4fc812b --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesFolderGenerator.cpp @@ -0,0 +1,435 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesFolderGenerator.cpp + * + * Created on: 2011. 10. 28. + * Author: sangtai + */ + +#include "StorageChangesFolderGenerator.h" +#include "StorageChangesFolderFilterValidatorFactory.h" + +#include "IMessagingTypes.h" + +#include + +#include + +using namespace std; +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + + const std::string StorageChangesFolderGenerator::STRING_MATCH_EXCACTLY = "EXACTLY"; + const std::string StorageChangesFolderGenerator::STRING_MATCH_CONTAINS = "CONTAINS"; + const std::string StorageChangesFolderGenerator::STRING_MATCH_STARTSWITH = "STARTSWITH"; + const std::string StorageChangesFolderGenerator::STRING_MATCH_ENDSWITH = "ENDSWITH"; +// const std::string StorageChangesFolderGenerator::STRING_MATCH_CASESENSITIVE = "CASESENSITIVE"; + + const int StorageChangesFolderGenerator::MESSAGE_TYPE_NOT_INITIALIZED = -1; + + StorageChangesFolderGenerator::StorageChangesFolderGenerator(Api::Messaging::IMessageFolderPtr folder):m_messageType(MESSAGE_TYPE_NOT_INITIALIZED) { + + m_id = folder->getId(); + m_parentid = folder->getParentId(); + m_accountid = folder->getAccountId(); + m_contestType = (unsigned short)folder->getContentType(); + m_name = folder->getName(); + m_path = folder->getPath(); + m_type = (unsigned short)folder->getType(); + m_synchronizable = folder->getSynchronizable(); + + LogDebug("m_type:" << m_type ); + + } + + StorageChangesFolderGenerator::~StorageChangesFolderGenerator() { + } + + + void StorageChangesFolderGenerator::visitPreComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + m_operand.push_back(leftblank); + LogDebug("Left_blank"); + LogDebug(">>>"); + } + + void StorageChangesFolderGenerator::visitInComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + if(type == UNION_FILTER ){ + LogDebug("UNION_FILTER"); + m_operand.push_back(operandUnion); + }else if(type == INTERSECTION_FILTER){ + LogDebug("INTERSECTION_FILTER"); + m_operand.push_back(operandIntersection); + }else{ + LogError("[ERROR] invalid Filter type:" << type); + } + + LogDebug(">>>"); + } + + void StorageChangesFolderGenerator::visitPostComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + bool data1, data2; + do + { + LogDebug("m_result size =" << m_result.size()); + data1 = m_result.back(); + m_result.pop_back(); + data2 = m_result.back(); + m_result.pop_back(); + LogDebug("m_result size =" << m_result.size()); + LogDebug("m_operand.back() =" << m_operand.back()); + LogDebug("m_operand size =" << m_operand.size()); + if(m_operand.back() == operandUnion) + { + LogDebug("Union"); + LogDebug("data1 = " << data1); + LogDebug("data2 = " << data2); + LogDebug("data1 || data2 = " << (data1 || data2)); + m_operand.pop_back(); + m_result.push_back(data1 || data2); + LogDebug("result" << m_result.back()); + LogDebug("m_result size =" << m_result.size()); + } + else if(m_operand.back() == operandIntersection) + { + LogDebug("Intersection"); + LogDebug("data1 = " << data1); + LogDebug("data2 = " << data2); + LogDebug("data1 && data2 = " << (data1 && data2)); + m_operand.pop_back(); + m_result.push_back(data1 && data2); + LogDebug("result " << m_result.back()); + LogDebug("m_result size =" << m_result.size()); + + } + }while(m_operand.back() != leftblank); + m_operand.pop_back(); + LogDebug("elase leftblank from m_operand"); + LogDebug("m_operand size =" << m_operand.size()); + LogDebug(">>>"); + } + + bool StorageChangesFolderGenerator::getMatchExactlyClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string valueString = value->toString(); + LogDebug("<<< attrName : " << attrName); + LogDebug("<<< valueString : " << valueString); + LogDebug("<<< attrName.compare(valueString) : " << attrName.compare(valueString)); + + if(attrName.compare(valueString) == 0) + { + LogDebug("<<< getMatchExactlyClause SAME >>>"); + return TRUE; + } + else{ + LogDebug("<<< getMatchExactlyClause DIFF >>>"); + return FALSE; + } + } + + bool StorageChangesFolderGenerator::getMatchContainsClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string valueString = value->toString(); + LogDebug("<<< attrName : " << attrName); + LogDebug("<<< valueString : " << valueString); + LogDebug("<<< attrName.find(valueString) : " << attrName.find(valueString)); + + if(attrName.find(valueString) != std::string::npos) + { + LogDebug("<<< getMatchContainsClause CONTAINS >>>"); + return TRUE; + }else{ + LogDebug("<<< getMatchContainsClause NOT CONTAINS >>>"); + return FALSE; + } + } + + bool StorageChangesFolderGenerator::getMatchStartwithClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string valueString = value->toString(); + LogDebug("<<< attrName : " << attrName); + LogDebug("<<< valueString : " << valueString); + LogDebug("<<< attrName.compare(0,valueString.size(), valueString) : " << attrName.compare(0,valueString.size(), valueString)); + + + if(attrName.size()-valueString.size() < 0) + return FALSE; + + if(attrName.compare(0,valueString.size(), valueString) == 0) + { + LogDebug("<<< getMatchStartwithClause START WITH >>>"); + return TRUE; + } + else{ + LogDebug("<<< getMatchStartwithClause NOT START WITH >>>"); + return FALSE; + } + } + + bool StorageChangesFolderGenerator::getMatchEndwithClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string valueString = value->toString(); + + LogDebug("<<< attrName : " << attrName); + LogDebug("<<< valueString : " << valueString); + LogDebug("<<< attrName.compare(attrName.size()-valueString.size(),valueString.size(), valueString) : " << attrName.compare(attrName.size()-valueString.size(),valueString.size(), valueString)); + + + if(attrName.size()-valueString.size() < 0) + return FALSE; + + if(attrName.compare(attrName.size()-valueString.size(),valueString.size(), valueString) == 0 ) + { + LogDebug("<<< getMatchEndwithClause END WITH >>>"); + return TRUE; + } + else{ + LogDebug("<<< getMatchEndwithClause NOT END WITH >>>"); + return FALSE; + } + } + + void StorageChangesFolderGenerator::visitAttribute(std::string& attrName, + Api::Tizen::AnyArrayPtr& values, std::string& matchFlag, bool caseSensitive, int depth){ + LogDebug("<<< attrName:[" << attrName << "], matchFlag:[" << matchFlag << "]"); + LogDebug("values->size():" << values->size()); + + Api::Tizen::FilterType filterType = UNION_FILTER; + + if(matchFlag.compare("EXIST")==0){ + //TODO implement for EXIST + }else if(values->size() == 1){ + AnyPtr matchValue = values->at(0); + visitAttributeEach(attrName, matchValue, matchFlag, depth); + }else{ + visitPreComposite(filterType, depth); + + AnyArray::iterator iter; + for(iter=values->begin(); iter!= values->end(); iter++){ + + if(iter != values->begin()){ + + visitInComposite(filterType, depth); + } + + AnyPtr matchValue = *iter; + visitAttributeEach(attrName, matchValue, matchFlag, depth); + } + + visitPostComposite(filterType, depth); + } + LogDebug(">>>"); + } + + void StorageChangesFolderGenerator::visitAttributeEach(std::string& attrName, Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth){ + LogDebug("<<< attrName:[" << attrName << "], value:[" << value->toString() << "]"); + std::string valueString; + +// Check Folder_type and filter_type + if(attrName.compare("accountid")==0){ + LogDebug("<<< value:[" << value << "]"); + int nType = atoi(value->toString().c_str()); + if((int)m_accountid == nType) + { + m_result.push_back(TRUE); + LogDebug("<<< accountid is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< accountid is different"); + } + return; + } + if(attrName.compare("contestType")==0){ + LogDebug("<<< value:[" << value << "]"); + std::string convertType = value->toString(); + int nType = convertMessageType(convertType); + if((int)m_contestType == nType) + { + m_result.push_back(TRUE); + LogDebug("<<< contestType is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< contestType is different"); + } + return; + } + if(attrName.compare("type")==0){ + LogDebug("<<< value:[" << value << "]"); + std::string convertType = value->toString(); + int nType = convertFolderType(convertType); + if((int)m_type == nType) + { + m_result.push_back(TRUE); + LogDebug("<<< type is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< type is different"); + } + return; + } + if(attrName.compare("synchronizable")==0){ + LogDebug("<<< value:[" << value << "]"); + int nType = value->toString().compare("true"); + if((int)m_synchronizable == nType) + { + m_result.push_back(TRUE); + LogDebug("<<< synchronizable is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< synchronizable is different"); + } + return; + } + + if(attrName.compare("name")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_name:[" << m_name << "]"); + + valueString = m_name; + if(getMatchFlagResult(value, valueString, matchFlag)) + { + m_result.push_back(TRUE); + LogDebug("<<< name is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< name is different"); + } + return; + } + + if(attrName.compare("path")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_path:[" << m_path << "]"); + + valueString = m_path; + if(getMatchFlagResult(value, valueString, matchFlag)) + { + m_result.push_back(TRUE); + LogDebug("<<< path is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< path is different"); + } + return; + } + + LogDebug(">>>"); + } + + int StorageChangesFolderGenerator::convertMessageType(std::string& stringType){ + LogDebug("<<< stringType:[" << stringType << "]"); + + int retMessageType = -1; + + if(stringType.compare("SMS") ==0){ + retMessageType = Api::Messaging::SMS; + }else if(stringType.compare("MMS") ==0){ + retMessageType = Api::Messaging::MMS; + }else if(stringType.compare("EMAIL") ==0){ + retMessageType = Api::Messaging::EMAIL; + }else{ + LogError("invalid type:[" << stringType << "]"); + return -1; + } + + LogDebug(">>> retMessageType:" << retMessageType); + return retMessageType; + } + + int StorageChangesFolderGenerator::convertFolderType(std::string& stringType){ + LogDebug("<<< stringType:[" << stringType << "]"); + + int retMessageType = -1; + + if(stringType.compare("INBOX") ==0){ + retMessageType = Api::Messaging::INBOX; + }else if(stringType.compare("OUTBOX") ==0){ + retMessageType = Api::Messaging::OUTBOX; + }else if(stringType.compare("DRAFTBOX") ==0){ + retMessageType = Api::Messaging::DRAFTBOX; + }else if(stringType.compare("SENTBOX") ==0){ + retMessageType = Api::Messaging::SENTBOX; + }else{ + LogError("invalid type:[" << stringType << "]"); + return -1; + } + + LogDebug(">>> retMessageType:" << retMessageType); + return retMessageType; + } + + + void StorageChangesFolderGenerator::visitAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth) { + LogDebug("<<< NOT SUPPROTED"); + LogDebug(">>>"); + m_result.push_back(FALSE); + } + + bool StorageChangesFolderGenerator::getMatchFlagResult(Api::Tizen::AnyPtr& value, std::string& valueString, std::string& matchFlag) + { + std::vector::iterator iter; + bool result = FALSE; + if(matchFlag.compare(STRING_MATCH_EXCACTLY) == 0){ + LogDebug("STRING_MATCH_EXCACTLY"); + result = result || getMatchExactlyClause(valueString, value); + }else if(matchFlag.compare(STRING_MATCH_CONTAINS) == 0){ + LogDebug("STRING_MATCH_CONTAINS"); + result = result || getMatchContainsClause(valueString, value); + }else if(matchFlag.compare(STRING_MATCH_STARTSWITH) == 0){ + LogDebug("STRING_MATCH_STARTSWITH"); + result = result || getMatchStartwithClause(valueString, value); + }else if(matchFlag.compare(STRING_MATCH_ENDSWITH) == 0){ + LogDebug("STRING_MATCH_ENDSWITH"); + result = result || getMatchEndwithClause(valueString, value); + }else{ + LogDebug("[ERROR]invalid match flag : iter:" << *iter); + } + return result; + } + + bool StorageChangesFolderGenerator::getCompareResult() + { + bool result; + LogDebug("m_result.size() " << m_result.size()); + result = m_result.back(); + m_result.pop_back(); + LogDebug("result = " << result); + return result; + } +} + } //namespace Platform +} //namespace WrtPlugins diff --git a/src/platform/API/Messaging/StorageChangesFolderGenerator.h b/src/platform/API/Messaging/StorageChangesFolderGenerator.h new file mode 100755 index 0000000..b7a30c9 --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesFolderGenerator.h @@ -0,0 +1,108 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesFolderGenerator.h + * + * Created on: 2011. 10. 28. + * Author: sangtai + */ + +#ifndef STORAGECHANGESFOLDERGENERATOR_H_ +#define STORAGECHANGESFOLDERGENERATOR_H_ + +#include +#include +#include + + +#include + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + +// using namespace std; + + class StorageChangesFolderGenerator: public TizenApis::Api::Tizen::IFilterVisitor{ + public: + + enum operandType + { + leftblank = 1, + rightblank = 2, + operandUnion = 3, + operandIntersection = 4 + }; + + StorageChangesFolderGenerator(Api::Messaging::IMessageFolderPtr conv); + virtual ~StorageChangesFolderGenerator(); + + void visitPreComposite(Api::Tizen::FilterType& type, int depth); + void visitInComposite(Api::Tizen::FilterType& type, int depth); + void visitPostComposite(Api::Tizen::FilterType& type, int depth); + void visitAttribute(std::string& attrName, + Api::Tizen::AnyArrayPtr& values, std::string& matchFlag, bool caseSensitive, int depth); + void visitAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth); + bool getMatchFlagResult(Api::Tizen::AnyPtr& value, std::string& valueString, std::string& matchFlag); + bool getCompareResult(); + + private: + bool getMatchExactlyClause(std::string& attrName, Api::Tizen::AnyPtr& value); + bool getMatchContainsClause(std::string& attrName, Api::Tizen::AnyPtr& value); + bool getMatchStartwithClause(std::string& attrName, Api::Tizen::AnyPtr& value); + bool getMatchEndwithClause(std::string& attrName, Api::Tizen::AnyPtr& value); + + void visitAttributeEach(std::string& attrName, Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth); + int convertMessageType(std::string& stringType); + int convertFolderType(std::string& stringType); + + + private: + int m_messageType; + + std::vector typeVector; + std::map attributeMap; + + std::vector m_result; + std::vector m_operand; + + unsigned long m_id; + unsigned long m_parentid; + unsigned long m_accountid; +// Api::Messaging::MessageType m_contestType; + unsigned short m_contestType; + std::string m_name; + std::string m_path; +// Api::Messaging::FolderType m_type; + unsigned short m_type; + bool m_synchronizable; + + static const std::string STRING_MATCH_EXCACTLY; + static const std::string STRING_MATCH_CONTAINS; + static const std::string STRING_MATCH_STARTSWITH; + static const std::string STRING_MATCH_ENDSWITH; + static const std::string STRING_MATCH_CASESENSITIVE; + + static const int MESSAGE_TYPE_NOT_INITIALIZED; + + }; + + typedef DPL::SharedPtr StorageChangesFolderGeneratorPtr; + } // namespace Platform +} // namespace WrtPlugins +} +#endif /* MESSAGEQUERYGENERATOR_H_ */ diff --git a/src/platform/API/Messaging/StorageChangesMessageFilterValidator.cpp b/src/platform/API/Messaging/StorageChangesMessageFilterValidator.cpp new file mode 100755 index 0000000..e8ca819 --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesMessageFilterValidator.cpp @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesMessageFilterValidator.cpp + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#include "StorageChangesMessageFilterValidator.h" +#include "StorageChangesMessageFilterValidatorFactory.h" + +#include + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + StorageChangesMessageFilterValidator::StorageChangesMessageFilterValidator(PropertyStructArray properties, + MatchFlagStrArray matchFlag):FilterValidator(properties, matchFlag){ + m_isTypeSetted = false; + } + + StorageChangesMessageFilterValidator::~StorageChangesMessageFilterValidator(){ + } + + bool StorageChangesMessageFilterValidator::validateAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue){ + bool retVal = false; + if(attrName.compare(StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_TIMESTAMP)!=0){ + LogError(">>> [ERROR] Not Supported attribute :[" << attrName << "]"); + return false; + } + + retVal = FilterValidator::validateAttributeRange(attrName, initialValue, endValue); + return retVal; + } + + //TODO Implement + bool StorageChangesMessageFilterValidator::validateAttribute(std::string& attrName, Api::Tizen::AnyArrayPtr& values, + std::string& matchFlag, bool caseSensitive, int depth){ + bool retBool = false; + + retBool = FilterValidator::validateAttribute(attrName, values, matchFlag, caseSensitive, depth); + LogDebug(">>> retBool:" << retBool); + return retBool; + } + } + } + +} diff --git a/src/platform/API/Messaging/StorageChangesMessageFilterValidator.h b/src/platform/API/Messaging/StorageChangesMessageFilterValidator.h new file mode 100755 index 0000000..1683625 --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesMessageFilterValidator.h @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesMessageFilterValidator.h + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#ifndef STORAGECHANGESMESSAGEFILTERVALIDATOR_H_ +#define STORAGECHANGESMESSAGEFILTERVALIDATOR_H_ + +#include + + +namespace TizenApis { + + namespace Platform { + + namespace Messaging { + + class StorageChangesMessageFilterValidator: public Api::Tizen::FilterValidator { + private: + bool m_isTypeSetted; + + public: + StorageChangesMessageFilterValidator(Api::Tizen::PropertyStructArray properties, + Api::Tizen::MatchFlagStrArray matchFlag); + + virtual ~StorageChangesMessageFilterValidator(); + + // validate AttributeRangeFilter + virtual bool validateAttributeRange(std::string& attrName, + Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue); + + virtual bool validateAttribute(std::string& attrName, Api::Tizen::AnyArrayPtr& values, + std::string& matchFlag, bool caseSensitive, int depth=0); + + + + }; + + typedef DPL::SharedPtr StorageChangesMessageFilterValidatorPtr; + } +} +} + +#endif diff --git a/src/platform/API/Messaging/StorageChangesMessageFilterValidatorFactory.cpp b/src/platform/API/Messaging/StorageChangesMessageFilterValidatorFactory.cpp new file mode 100755 index 0000000..2bae4a8 --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesMessageFilterValidatorFactory.cpp @@ -0,0 +1,78 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesMessageFilterValidatorFactory.cpp + * + * Created on: 2011. 10. 27. + * Author: sangtai + */ + +#include "StorageChangesMessageFilterValidatorFactory.h" + +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + const std::string StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_TYPE = "type"; + const std::string StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_FOLDER = "folder"; + const std::string StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_TIMESTAMP = "timestamp"; + const std::string StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_FROM = "from"; + const std::string StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_TO = "to"; + const std::string StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_CC = "cc"; + const std::string StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_BCC = "bcc"; + const std::string StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_BODY = "body"; + const std::string StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_IS_READ = "isRead"; + const std::string StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_PRIORITY = "priority"; + const std::string StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_SUBJECT = "subject"; + + + static PropertyStructArray properties = + { + {"type", Api::Tizen::PrimitiveType_String}, + {"folder", Api::Tizen::PrimitiveType_String}, + {StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_TIMESTAMP.c_str(), Api::Tizen::PrimitiveType_Time}, + {"from", Api::Tizen::PrimitiveType_String}, + {"to", Api::Tizen::PrimitiveType_String}, + {"cc", Api::Tizen::PrimitiveType_String}, + {"bcc", Api::Tizen::PrimitiveType_String}, + {"body", Api::Tizen::PrimitiveType_String}, + {"isRead", Api::Tizen::PrimitiveType_Number}, + {StorageChangesMessageFilterValidatorFactory::ATTRIBUTE_PRIORITY.c_str(), Api::Tizen::PrimitiveType_Number}, + {"subject", Api::Tizen::PrimitiveType_String}, + {0, Api::Tizen::PrimitiveType_Notype} + }; + + static MatchFlagStrArray matchFlag{ + "EXACTLY", + "CONTAINS", + "STARTSWITH", + "ENDSWITH", + 0 + }; + + StorageChangesMessageFilterValidatorPtr StorageChangesMessageFilterValidatorFactory::getStorageChangesMessageFilterValidator() + { + static StorageChangesMessageFilterValidatorPtr theInstance = + StorageChangesMessageFilterValidatorPtr(new StorageChangesMessageFilterValidator(properties, matchFlag)); + + return theInstance; + } + + } + } //naspace Platform +} //naspace WrtPlugins diff --git a/src/platform/API/Messaging/StorageChangesMessageFilterValidatorFactory.h b/src/platform/API/Messaging/StorageChangesMessageFilterValidatorFactory.h new file mode 100755 index 0000000..17199ac --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesMessageFilterValidatorFactory.h @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesMessageFilterValidatorFactory.h + * + * Created on: 2011. 10. 27. + * Author: sangtai + */ + +#ifndef STORAGECHANGESMESSAGINGFILTERVALIDATORFACTORY_H_ +#define STORAGECHANGESMESSAGINGFILTERVALIDATORFACTORY_H_ + +#include +#include "StorageChangesMessageFilterValidator.h" + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + class StorageChangesMessageFilterValidatorFactory { + private: + StorageChangesMessageFilterValidatorFactory() + { + } + + public: + static StorageChangesMessageFilterValidatorPtr getStorageChangesMessageFilterValidator(); + + public: +// static const std::string ATTRIBUTE_ID; + static const std::string ATTRIBUTE_TYPE; + static const std::string ATTRIBUTE_FOLDER; + static const std::string ATTRIBUTE_TIMESTAMP; + static const std::string ATTRIBUTE_FROM; + static const std::string ATTRIBUTE_TO; + static const std::string ATTRIBUTE_CC; + static const std::string ATTRIBUTE_BCC; + static const std::string ATTRIBUTE_BODY; + static const std::string ATTRIBUTE_IS_READ; + static const std::string ATTRIBUTE_PRIORITY; + static const std::string ATTRIBUTE_SUBJECT; + }; + + } + } //Platform +} + +#endif /* MESSAGINGFILTERVALIDATORFACTORY_H_ */ diff --git a/src/platform/API/Messaging/StorageChangesMessageGenerator.cpp b/src/platform/API/Messaging/StorageChangesMessageGenerator.cpp new file mode 100755 index 0000000..73f2a61 --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesMessageGenerator.cpp @@ -0,0 +1,669 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesMessageGenerator.cpp + * + * Created on: 2011. 10. 28. + * Author: sangtai + */ + +#include "StorageChangesMessageGenerator.h" +#include "StorageChangesMessageFilterValidatorFactory.h" +#include "API/Messaging/ConversationFilterValidatorFactory.h" + +#include "IMessagingTypes.h" + +#include + +#include + +using namespace std; +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + const std::string StorageChangesMessageGenerator::STRING_MATCH_EXCACTLY = "EXACTLY"; + const std::string StorageChangesMessageGenerator::STRING_MATCH_CONTAINS = "CONTAINS"; + const std::string StorageChangesMessageGenerator::STRING_MATCH_STARTSWITH = "STARTSWITH"; + const std::string StorageChangesMessageGenerator::STRING_MATCH_ENDSWITH = "ENDSWITH"; +// const std::string StorageChangesMessageGenerator::STRING_MATCH_CASESENSITIVE = "CASESENSITIVE"; + + const int StorageChangesMessageGenerator::MESSAGE_TYPE_NOT_INITIALIZED = -1; + + StorageChangesMessageGenerator::StorageChangesMessageGenerator(Api::Messaging::IMessagePtr msg):m_messageType(MESSAGE_TYPE_NOT_INITIALIZED) { + + m_type = msg->getMessageType(); + m_folder = msg->getCurrentFolder(); + m_dateTime = msg->getDateTime(); + m_from = msg->getFrom(); + + Recipents = msg->getToRecipientsPtr(); + + if(m_type == Api::Messaging::SMS) + { + LogDebug("size :" << Recipents->getRecipientSize()); + + if(Recipents->getRecipientSize()>0) + { + m_to = Recipents->getRecipientsRef(); + LogDebug("m_to :" << m_to[0]); + } + } + else if(m_type == Api::Messaging::MMS) + { + LogDebug("to size :" << Recipents->getRecipientSize()); + + Api::Messaging::IMmsPtr mms = DPL::DynamicPointerCast(msg); + if(Recipents->getRecipientSize() > 0) + { + m_to = Recipents->getRecipientsRef(); + LogDebug("m_to :" << m_to[0]); + } + + Recipents = mms->getCcRecipientsPtr(); + LogDebug("cc size :" << Recipents->getRecipientSize()); + + if(Recipents->getRecipientSize() > 0) + { + m_cc = Recipents->getRecipientsRef(); + } + + Recipents = mms->getBccRecipientsPtr(); + LogDebug("bcc size :" << Recipents->getRecipientSize()); + + if(Recipents->getRecipientSize() > 0) + { + m_bcc = Recipents->getRecipientsRef(); + } + } + else if(m_type == Api::Messaging::EMAIL) + { + LogDebug("to size :" << Recipents->getRecipientSize()); + + Api::Messaging::IEmailPtr email = DPL::DynamicPointerCast(msg); + if(Recipents->getRecipientSize() > 0) + { + m_to = Recipents->getRecipientsRef(); + LogDebug("m_to :" << m_to[0]); + } + + Recipents = email->getCcRecipientsPtr(); + LogDebug("cc size :" << Recipents->getRecipientSize()); + + if(Recipents->getRecipientSize() > 0) + { + m_cc = Recipents->getRecipientsRef(); + } + + Recipents = email->getBccRecipientsPtr(); + LogDebug("bcc size :" << Recipents->getRecipientSize()); + + if(Recipents->getRecipientSize() > 0) + { + m_bcc = Recipents->getRecipientsRef(); + } + + } + + + + m_body = msg->getBody(); + m_isRead = msg->isRead(); + m_priority = msg->getPriority(); + m_subject = msg->getSubject(); + + LogDebug("m_type:" << m_type ); + LogDebug("m_folder:" << m_folder ); + LogDebug("m_dateTime year:" << m_dateTime.tm_year + 1900 ); + LogDebug("m_dateTime mon:" << m_dateTime.tm_mon ); + LogDebug("m_dateTime day:" << m_dateTime.tm_mday ); + LogDebug("m_dateTime hour:" << m_dateTime.tm_hour ); + LogDebug("m_dateTime min:" << m_dateTime.tm_min ); + LogDebug("m_dateTime sec:" << m_dateTime.tm_sec ); + LogDebug("m_from:" << m_from ); + LogDebug("m_body:" << m_body ); + LogDebug("m_isRead:" << m_isRead ); + LogDebug("m_priority:" << m_priority ); + LogDebug("m_subject:" << m_subject ); + + } + + StorageChangesMessageGenerator::~StorageChangesMessageGenerator() { + } + + void StorageChangesMessageGenerator::visitPreComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + m_operand.push_back(leftblank); + LogDebug("Left_blank"); + LogDebug(">>>"); + } + + void StorageChangesMessageGenerator::visitInComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + if(type == UNION_FILTER ){ + LogDebug("UNION_FILTER"); + m_operand.push_back(operandUnion); + }else if(type == INTERSECTION_FILTER){ + LogDebug("INTERSECTION_FILTER"); + m_operand.push_back(operandIntersection); + }else{ + LogError("[ERROR] invalid Filter type:" << type); + } + + LogDebug(">>>"); + } + + void StorageChangesMessageGenerator::visitPostComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + bool data1, data2; + do + { + LogDebug("m_result size =" << m_result.size()); + data1 = m_result.back(); + m_result.pop_back(); + data2 = m_result.back(); + m_result.pop_back(); + LogDebug("m_result size =" << m_result.size()); + LogDebug("m_operand.back() =" << m_operand.back()); + LogDebug("m_operand size =" << m_operand.size()); + if(m_operand.back() == operandUnion) + { + LogDebug("Union"); + LogDebug("data1 = " << data1); + LogDebug("data2 = " << data2); + LogDebug("data1 || data2 = " << (data1 || data2)); + m_operand.pop_back(); + m_result.push_back(data1 || data2); + LogDebug("result" << m_result.back()); + LogDebug("m_result size =" << m_result.size()); + } + else if(m_operand.back() == operandIntersection) + { + LogDebug("Intersection"); + LogDebug("data1 = " << data1); + LogDebug("data2 = " << data2); + LogDebug("data1 && data2 = " << (data1 && data2)); + m_operand.pop_back(); + m_result.push_back(data1 && data2); + LogDebug("result" << m_result.back()); + LogDebug("m_result size =" << m_result.size()); + + } + }while(m_operand.back() != leftblank); + m_operand.pop_back(); + LogDebug("elase leftblank from m_operand"); + LogDebug("m_operand size =" << m_operand.size()); + LogDebug(">>>"); + } + + struct tm StorageChangesMessageGenerator::convertToTimeFormat(const std::string& timeString){ + LogDebug("<<< timeString:[" << timeString << "]"); + + struct tm tm_Time; + + int nextStart = 0; + + int yearLength = 4; + tm_Time.tm_year = atoi(timeString.substr(0, yearLength).c_str())-1900; + nextStart = nextStart + yearLength; + LogDebug("<<< tm_Time.tm_year:[" << tm_Time.tm_year << "]"); + + int monthLength = 2; + tm_Time.tm_mon = atoi(timeString.substr(nextStart, monthLength).c_str()); + nextStart = nextStart + monthLength; + LogDebug("<<< initTime.tm_mon:[" << tm_Time.tm_mon << "]"); + + int dateLength = 2; + tm_Time.tm_mday = atoi(timeString.substr(nextStart, dateLength).c_str()); + nextStart = nextStart + dateLength; + LogDebug("<<< initTime.tm_mday:[" << tm_Time.tm_mday << "]"); + + int hourLength = 2; + tm_Time.tm_hour = atoi(timeString.substr(nextStart, hourLength).c_str()); + nextStart = nextStart + hourLength; + LogDebug("<<< initTime.tm_hour:[" << tm_Time.tm_hour << "]"); + + int minuteLength = 2; + tm_Time.tm_min = atoi(timeString.substr(nextStart, minuteLength).c_str()); + nextStart = nextStart + minuteLength; + LogDebug("<<< initTime.tm_min:[" << tm_Time.tm_min << "]"); + + int secondLength = 2; + tm_Time.tm_sec = atoi(timeString.substr(nextStart, secondLength).c_str()); + LogDebug("<<< initTime.tm_sec:[" << tm_Time.tm_sec << "]"); + + return tm_Time; + } + + bool StorageChangesMessageGenerator::getMatchExactlyClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string valueString = value->toString(); + LogDebug("<<< attrName : " << attrName); + LogDebug("<<< valueString : " << valueString); + LogDebug("<<< attrName.compare(valueString) : " << attrName.compare(valueString)); + + if(attrName.compare(valueString) == 0) + { + LogDebug("<<< getMatchExactlyClause SAME >>>"); + return TRUE; + } + else{ + LogDebug("<<< getMatchExactlyClause DIFF >>>"); + return FALSE; + } + } + + bool StorageChangesMessageGenerator::getMatchContainsClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string valueString = value->toString(); + LogDebug("<<< attrName : " << attrName); + LogDebug("<<< valueString : " << valueString); + LogDebug("<<< attrName.find(valueString) : " << attrName.find(valueString)); + + if(attrName.find(valueString) != std::string::npos) + { + LogDebug("<<< getMatchContainsClause CONTAINS >>>"); + return TRUE; + }else{ + LogDebug("<<< getMatchContainsClause NOT CONTAINS >>>"); + return FALSE; + } + } + + bool StorageChangesMessageGenerator::getMatchStartwithClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string valueString = value->toString(); + LogDebug("<<< attrName : " << attrName); + LogDebug("<<< valueString : " << valueString); + LogDebug("<<< attrName.compare(0,valueString.size(), valueString) : " << attrName.compare(0,valueString.size(), valueString)); + + + if(attrName.size()-valueString.size() < 0) + return FALSE; + + if(attrName.compare(0,valueString.size(), valueString) == 0) + { + LogDebug("<<< getMatchStartwithClause START WITH >>>"); + return TRUE; + } + else{ + LogDebug("<<< getMatchStartwithClause NOT START WITH >>>"); + return FALSE; + } + } + + bool StorageChangesMessageGenerator::getMatchEndwithClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string valueString = value->toString(); + + LogDebug("<<< attrName : " << attrName); + LogDebug("<<< valueString : " << valueString); + LogDebug("<<< attrName.compare(attrName.size()-valueString.size(),valueString.size(), valueString) : " << attrName.compare(attrName.size()-valueString.size(),valueString.size(), valueString)); + + + if(attrName.size()-valueString.size() < 0) + return FALSE; + + if(attrName.compare(attrName.size()-valueString.size(),valueString.size(), valueString) == 0 ) + { + LogDebug("<<< getMatchEndwithClause END WITH >>>"); + return TRUE; + } + else{ + LogDebug("<<< getMatchEndwithClause NOT END WITH >>>"); + return FALSE; + } + } + + bool StorageChangesMessageGenerator::getBetweenRangeClause(struct tm initialValue, struct tm endValue) + { + time_t init_time, mid_time, end_time; + init_time = mktime(&initialValue); + mid_time = mktime(&m_dateTime); + end_time = mktime(&endValue); + LogDebug("<<< mktime(initialValue):[" << init_time << "]"); + LogDebug("<<< mktime(m_dateTime):[" << mid_time << "]"); + LogDebug("<<< mktime(endValue):[" << end_time << "]"); + LogDebug("<<< mid_time - init_time:[" << mid_time - init_time << "]"); + LogDebug("<<< end_time - mid_time:[" << end_time - mid_time << "]"); + + if(((mid_time - init_time) >= 0 ) && ((end_time - mid_time) >= 0 )) + return TRUE; + else + return FALSE; + + } + + void StorageChangesMessageGenerator::visitAttribute(std::string& attrName, + Api::Tizen::AnyArrayPtr& values, std::string& matchFlag, bool caseSensitive, int depth){ + LogDebug("<<< attrName:[" << attrName << "], matchFlag:[" << matchFlag << "]"); + LogDebug("values->size():" << values->size()); + + Api::Tizen::FilterType filterType = UNION_FILTER; + + if(matchFlag.compare("EXIST")==0){ + //TODO implement for EXIST + }else if(values->size() == 1){ + AnyPtr matchValue = values->at(0); + visitAttributeEach(attrName, matchValue, matchFlag, depth); + }else{ + visitPreComposite(filterType, depth); + + AnyArray::iterator iter; + for(iter=values->begin(); iter!= values->end(); iter++){ + + if(iter != values->begin()){ + + visitInComposite(filterType, depth); + } + + AnyPtr matchValue = *iter; + visitAttributeEach(attrName, matchValue, matchFlag, depth); + } + + visitPostComposite(filterType, depth); + } + LogDebug(">>>"); + } + + void StorageChangesMessageGenerator::visitAttributeEach(std::string& attrName, Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth){ + LogDebug("<<< attrName:[" << attrName << "], value:[" << value->toString() << "]"); + std::string valueString; + +// Check msg_type and filter_type + if(attrName.compare("type")==0){ + LogDebug("<<< value:[" << value << "]"); + m_currentType = value->toString(); + m_messageType = convertMessageType(m_currentType); + if((int)m_type == m_messageType) + { + m_result.push_back(TRUE); + LogDebug("<<< Type is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< Type is different"); + } + return; + } + if(attrName.compare("folder")==0){ + LogDebug("<<< value:[" << value << "]"); + std::string convertType = value->toString(); + int nType = convertFolderType(convertType); + if((int)m_folder == nType) + { + m_result.push_back(TRUE); + LogDebug("<<< folder is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< folder is different"); + } + return; + } + if(attrName.compare("isRead")==0){ + LogDebug("<<< value:[" << value << "]"); + int nType = value->toString().compare("true"); + if((int)m_isRead == nType) + { + m_result.push_back(TRUE); + LogDebug("<<< isRead is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< isRead is different"); + } + return; + } + if(attrName.compare("priority")==0){ + LogDebug("<<< value:[" << value->toString() << "]"); + if(value->toString().compare("true") == 0) + { + if((int)m_priority == Api::Messaging::MessagePriority::Priority::HIGH) + { + m_result.push_back(TRUE); + LogDebug("<<< priority is HIGH"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< priority is LOW OR NORMAL"); + } + } + else + { + if((int)m_priority == Api::Messaging::MessagePriority::Priority::HIGH) + { + m_result.push_back(FALSE); + LogDebug("<<< priority is HIGH"); + } + else + { + m_result.push_back(TRUE); + LogDebug("<<< priority is LOW OR NORMAL"); + } + } + return; + } + if(attrName.compare("body")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_body:[" << m_body << "]"); + + valueString = m_body; + if(getMatchFlagResult(value, valueString, matchFlag)) + { + m_result.push_back(TRUE); + LogDebug("<<< body is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< body is different"); + } + return; + } + + if(attrName.compare("subject")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_subject:[" << m_subject << "]"); + + valueString = m_subject; + if(getMatchFlagResult(value, valueString, matchFlag)) + { + m_result.push_back(TRUE); + LogDebug("<<< subject is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< subject is different"); + } + return; + } + + if(attrName.compare("from")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_from:[" << m_from << "]"); + + valueString = m_from; + if(getMatchFlagResult(value, valueString, matchFlag)) + { + m_result.push_back(TRUE); + LogDebug("<<< from is same"); + } + else + { + m_result.push_back(FALSE); + LogDebug("<<< from is different"); + } + return; + } + + if(attrName.compare("to")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_to.size :[" << m_to.size() << "]"); + + bool result = FALSE; + for(unsigned int i=0; i < m_to.size(); i++) + { + valueString = m_to[i]; + result = result || getMatchFlagResult(value, valueString, matchFlag); + } + LogDebug("<<< to compare result is :" << result); + m_result.push_back(result); + return; + } + + if(attrName.compare("cc")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_cc.size :[" << m_cc.size() << "]"); + + bool result = FALSE; + for(unsigned int i=0; i < m_cc.size(); i++) + { + valueString = m_cc[i]; + result = result || getMatchFlagResult(value, valueString, matchFlag); + } + LogDebug("<<< cc compare result is : " << result); + m_result.push_back(result); + return; + } + + if(attrName.compare("bcc")==0){ + LogDebug("<<< value:[" << value << "]"); + LogDebug("<<< value->toString():[" << value->toString() << "]"); + LogDebug("<<< m_cc.size :[" << m_bcc.size() << "]"); + + bool result = FALSE; + for(unsigned int i=0; i < m_bcc.size(); i++) + { + valueString = m_bcc[i]; + result = result || getMatchFlagResult(value, valueString, matchFlag); + } + LogDebug("<<< bcc compare result is : " << result); + m_result.push_back(result); + return; + } + + LogDebug(">>>"); + } + + int StorageChangesMessageGenerator::convertMessageType(std::string& stringType){ + LogDebug("<<< stringType:[" << stringType << "]"); + + int retMessageType = -1; + + if(stringType.compare("SMS") ==0){ + retMessageType = Api::Messaging::SMS; + }else if(stringType.compare("MMS") ==0){ + retMessageType = Api::Messaging::MMS; + }else if(stringType.compare("EMAIL") ==0){ + retMessageType = Api::Messaging::EMAIL; + }else{ + LogError("invalid type:[" << stringType << "]"); + return -1; + } + + LogDebug(">>> retMessageType:" << retMessageType); + return retMessageType; + } + + int StorageChangesMessageGenerator::convertFolderType(std::string& stringType){ + LogDebug("<<< stringType:[" << stringType << "]"); + + int retMessageType = -1; + + if(stringType.compare("INBOX") ==0){ + retMessageType = Api::Messaging::INBOX; + }else if(stringType.compare("OUTBOX") ==0){ + retMessageType = Api::Messaging::OUTBOX; + }else if(stringType.compare("DRAFTBOX") ==0){ + retMessageType = Api::Messaging::DRAFTBOX; + }else if(stringType.compare("SENTBOX") ==0){ + retMessageType = Api::Messaging::SENTBOX; + }else{ + LogError("invalid type:[" << stringType << "]"); + return -1; + } + + LogDebug(">>> retMessageType:" << retMessageType); + return retMessageType; + } + + void StorageChangesMessageGenerator::visitAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth) { + struct tm startTime; + struct tm endTime; + bool result = FALSE; + + if(attrName.compare("timestamp")==0){ + startTime = convertToTimeFormat(initialValue->toString()); + endTime = convertToTimeFormat(endValue->toString()); + result = getBetweenRangeClause(startTime, endTime); + if(result == TRUE) + { + LogDebug("<<< timestamp is in range"); + m_result.push_back(TRUE); + }else{ + LogDebug("<<< timestamp is out of range"); + m_result.push_back(FALSE); + } + } + } + + bool StorageChangesMessageGenerator::getMatchFlagResult(Api::Tizen::AnyPtr& value, std::string& valueString, std::string& matchFlag) + { + std::vector::iterator iter; + bool result = FALSE; + if(matchFlag.compare(STRING_MATCH_EXCACTLY) == 0){ + LogDebug("STRING_MATCH_EXCACTLY"); + result = result || getMatchExactlyClause(valueString, value); + }else if(matchFlag.compare(STRING_MATCH_CONTAINS) == 0){ + LogDebug("STRING_MATCH_CONTAINS"); + result = result || getMatchContainsClause(valueString, value); + }else if(matchFlag.compare(STRING_MATCH_STARTSWITH) == 0){ + LogDebug("STRING_MATCH_STARTSWITH"); + result = result || getMatchStartwithClause(valueString, value); + }else if(matchFlag.compare(STRING_MATCH_ENDSWITH) == 0){ + LogDebug("STRING_MATCH_ENDSWITH"); + result = result || getMatchEndwithClause(valueString, value); + }else{ + LogDebug("[ERROR]invalid match flag : iter:" << *iter); + } + return result; + } + + bool StorageChangesMessageGenerator::getCompareResult() + { + bool result; + LogDebug("m_result.size() " << m_result.size()); + result = m_result.back(); + m_result.pop_back(); + LogDebug("result = " << result); + return result; + } + } + } //namespace Platform +} //namespace WrtPlugins diff --git a/src/platform/API/Messaging/StorageChangesMessageGenerator.h b/src/platform/API/Messaging/StorageChangesMessageGenerator.h new file mode 100755 index 0000000..4c50242 --- /dev/null +++ b/src/platform/API/Messaging/StorageChangesMessageGenerator.h @@ -0,0 +1,124 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * StorageChangesMessageGenerator.h + * + * Created on: 2011. 10. 28. + * Author: sangtai + */ + +#ifndef STORAGECHANGESMESSAGEGENERATOR_H_ +#define STORAGECHANGESMESSAGEGENERATOR_H_ + +#include +#include +#include + +#include + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + +// using namespace std; + + class StorageChangesMessageGenerator: public TizenApis::Api::Tizen::IFilterVisitor{ + public: + + enum operandType + { + leftblank = 1, + rightblank = 2, + operandUnion = 3, + operandIntersection = 4 + }; + + StorageChangesMessageGenerator(Api::Messaging::IMessagePtr msg); + virtual ~StorageChangesMessageGenerator(); + + void visitPreComposite(Api::Tizen::FilterType& type, int depth); + void visitInComposite(Api::Tizen::FilterType& type, int depth); + void visitPostComposite(Api::Tizen::FilterType& type, int depth); + void visitAttribute(std::string& attrName, + Api::Tizen::AnyArrayPtr& values, std::string& matchFlag, bool caseSensitive, int depth); + void visitAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth); + bool getMatchFlagResult(Api::Tizen::AnyPtr& value, std::string& valueString, std::string& matchFlag); + bool getCompareResult(); + int getMessageType(){ + return m_messageType; + }; + + private: + std::string convertToEmfAttrName(std::string attrName); + bool getMatchExactlyClause(std::string& attrName, Api::Tizen::AnyPtr& value); + bool getMatchContainsClause(std::string& attrName, Api::Tizen::AnyPtr& value); + bool getMatchStartwithClause(std::string& attrName, Api::Tizen::AnyPtr& value); + bool getMatchEndwithClause(std::string& attrName, Api::Tizen::AnyPtr& value); + bool getBetweenRangeClause(struct tm initialValue, struct tm endValue); + + void visitAttributeEach(std::string& attrName, Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth); + int convertMessageType(std::string& stringType); + int convertFolderType(std::string& stringType); + + struct tm convertToTimeFormat(const std::string& timeString); + std::string createTimeString(std::string& timeString); + std::string createFolderType(std::string& value); + std::string createPriorityType(std::string& value); + std::string createDateTimeType(Api::Tizen::AnyPtr& value); + void initAttributeMap(); + + + private: + int m_messageType; + + std::vector typeVector; + std::map attributeMap; + + std::vector m_result; + std::vector m_operand; + +// std::string m_id; + Api::Messaging::MessageType m_type; + Api::Messaging::FolderType m_folder; + struct tm m_dateTime; + std::string m_from; + std::vector m_to; + std::vector m_cc; + std::vector m_bcc; + std::string m_body; + bool m_isRead; + Api::Messaging::MessagePriority::Priority m_priority; + std::string m_subject; + + Api::Messaging::RecipientsPtr Recipents; + std::string m_currentType; + + static const std::string STRING_MATCH_EXCACTLY; + static const std::string STRING_MATCH_CONTAINS; + static const std::string STRING_MATCH_STARTSWITH; + static const std::string STRING_MATCH_ENDSWITH; + static const std::string STRING_MATCH_CASESENSITIVE; + + static const int MESSAGE_TYPE_NOT_INITIALIZED; + + }; + + typedef DPL::SharedPtr StorageChangesMessageGeneratorPtr; + } // namespace Platform +} // namespace WrtPlugins +} +#endif /* MESSAGEQUERYGENERATOR_H_ */ diff --git a/src/platform/API/Messaging/Subject.cpp b/src/platform/API/Messaging/Subject.cpp new file mode 100755 index 0000000..350f7c2 --- /dev/null +++ b/src/platform/API/Messaging/Subject.cpp @@ -0,0 +1,71 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Subject.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "Subject.h" + +using namespace std; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +Subject::Subject() : + m_subject(""), + m_validSubject(false) +{ +} + +Subject::~Subject() +{ +} + +void Subject::setSubject(const string& value) +{ + m_validSubject = false; + m_subject = value; +} + +string Subject::getSubject() const +{ + return m_subject; +} + +const std::string& Subject::getSubjectRef() const +{ + return m_subject; +} + +bool Subject::isSubjectValid() const +{ + return m_validSubject; +} + +void Subject::setSubjectValidity(bool state) +{ + m_validSubject = state; +} +} +} +} diff --git a/src/platform/API/Messaging/Subject.h b/src/platform/API/Messaging/Subject.h new file mode 100755 index 0000000..c2fdf14 --- /dev/null +++ b/src/platform/API/Messaging/Subject.h @@ -0,0 +1,86 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Subject.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef SUBJECT_H +#define SUBJECT_H + +#include +#include "IMessagingTypes.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class Subject +{ + private: // fields + /** + * abstract subject value of message + */ + std::string m_subject; + + /** + * information if abstract message body has been changed and need update + * in low level + */ + bool m_validSubject; + + public: // methods + + Subject(); + + virtual ~Subject(); + + /** + * setter of subject value + */ + void setSubject(const std::string& value); + + /** + * getter of subject value + */ + std::string getSubject() const; + + /** + * getter of subject value + */ + const std::string& getSubjectRef() const; + + /** + * check validity state + */ + bool isSubjectValid() const; + + /** + * setter for validity state + */ + void setSubjectValidity(bool state); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/ToRecipient.cpp b/src/platform/API/Messaging/ToRecipient.cpp new file mode 100755 index 0000000..2eed804 --- /dev/null +++ b/src/platform/API/Messaging/ToRecipient.cpp @@ -0,0 +1,86 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file ToRecipient.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include "ToRecipient.h" + +using namespace std; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +ToRecipient::ToRecipient() : + m_toRecipients(new Recipients()) +{ +} + +ToRecipient::~ToRecipient() +{ +} + +void ToRecipient::setToValidity(bool state) +{ + m_toRecipients->setValid(state); +} + +bool ToRecipient::getToValidity() const +{ + return m_toRecipients->isValid(); +} + +Recipients ToRecipient::getToRecipients() const +{ + return *m_toRecipients; +} + +RecipientsPtr ToRecipient::getToRecipientsPtr() const +{ + return m_toRecipients; +} + +void ToRecipient::appendToRecipients(const string & value) +{ + m_toRecipients->appendRecipient(value); +} + +void ToRecipient::appendToRecipients(const Recipients& value) +{ + LogDebug("enter, recipientCount=" << value.getRecipientSize()); + *m_toRecipients += value; +} + +void ToRecipient::removeToRecipients(const Recipients& value) +{ + *m_toRecipients -= value; +} + +void ToRecipient::setToRecipients(const Recipients& value) +{ + *m_toRecipients = value; +} +} +} +} diff --git a/src/platform/API/Messaging/ToRecipient.h b/src/platform/API/Messaging/ToRecipient.h new file mode 100755 index 0000000..61e390c --- /dev/null +++ b/src/platform/API/Messaging/ToRecipient.h @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file ToRecipient.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef TORECIPIENT_H +#define TORECIPIENT_H + +#include "Recipient.h" +#include + +namespace TizenApis { +namespace Api { +namespace Messaging { + +class ToRecipient +{ + private: // fields + + RecipientsPtr m_toRecipients; + + public: + + ToRecipient(); + + virtual ~ToRecipient(); + + void setToValidity(bool state); + + bool getToValidity() const; + + Recipients getToRecipients() const; + + RecipientsPtr getToRecipientsPtr() const; + + void appendToRecipients(const std::string & value); + + void appendToRecipients(const Recipients& value); + + void removeToRecipients(const Recipients& value); + + void setToRecipients(const Recipients& value); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/ValidityPeriodHours.cpp b/src/platform/API/Messaging/ValidityPeriodHours.cpp new file mode 100755 index 0000000..cc72b7f --- /dev/null +++ b/src/platform/API/Messaging/ValidityPeriodHours.cpp @@ -0,0 +1,64 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file ValidityPeriodHours.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "ValidityPeriodHours.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +ValidityPeriodHours::ValidityPeriodHours() : + m_validityPeriodHours(0), + m_validValidityPeriodHours(false) +{ +} + +ValidityPeriodHours::~ValidityPeriodHours() +{ +} + +void ValidityPeriodHours::setValidityPeriodHours(int value) +{ + m_validityPeriodHours = value; + m_validValidityPeriodHours = false; +} + +int ValidityPeriodHours::getValidityPeriodHours() const +{ + return m_validityPeriodHours; +} + +bool ValidityPeriodHours::isValidityPeriodHoursValid() const +{ + return m_validValidityPeriodHours; +} + +void ValidityPeriodHours::setValidityPeriodHoursValidity(bool state) +{ + m_validValidityPeriodHours = state; +} +} +} +} diff --git a/src/platform/API/Messaging/ValidityPeriodHours.h b/src/platform/API/Messaging/ValidityPeriodHours.h new file mode 100755 index 0000000..6781f81 --- /dev/null +++ b/src/platform/API/Messaging/ValidityPeriodHours.h @@ -0,0 +1,79 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file ValidityPeriodHours.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef VALIDITYPERIODHOURS_H +#define VALIDITYPERIODHOURS_H + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class ValidityPeriodHours +{ + private: // fields + + /** + * ValidityPeriodHours value + */ + int m_validityPeriodHours; + + /** + * information if abstract message ValidityPeriodHours has been changed and need update + * in low level + */ + bool m_validValidityPeriodHours; + + public: // methods + + ValidityPeriodHours(); + + virtual ~ValidityPeriodHours(); + + /** + * setter of ValidityPeriodHours value + */ + void setValidityPeriodHours(int value); + + /** + * getter of ValidityPeriodHours value + */ + int getValidityPeriodHours() const; + + /** + * check ValidityPeriodHours validity + * */ + bool isValidityPeriodHoursValid() const; + + /** + * set ValidityPeriodHours validity + * */ + void setValidityPeriodHoursValidity(bool state); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/VirtualMessage.cpp b/src/platform/API/Messaging/VirtualMessage.cpp new file mode 100755 index 0000000..712eacb --- /dev/null +++ b/src/platform/API/Messaging/VirtualMessage.cpp @@ -0,0 +1,89 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file VirtualMessage.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include "Commons/Exception.h" +#include "IMessage.h" +#include "VirtualMessage.h" + +using namespace std; + +namespace TizenApis { +namespace Api { +namespace Messaging { + +VirtualMessage::VirtualMessage() : + IMessage(VIRTUAL_MESSAGE, "") +{ +} + +VirtualMessage::~VirtualMessage() +{ +} + +int VirtualMessage::send() +{ + return -1; +} + +void VirtualMessage::sendCancel(int handle) +{ +} + +void VirtualMessage::update(bool /*draftsOnly*/) +{ +} + +void VirtualMessage::readAllData() +{ +} + +void VirtualMessage::moveToFolder(const FolderType newFolder) +{ +} + +void VirtualMessage::moveToFolder(const std::string& newFolder) +{ +} + +void VirtualMessage::copyToFolder(const FolderType newFolder) +{ +} + +void VirtualMessage::copyToFolder(const std::string& newFolder) +{ +} + +void VirtualMessage::remove() +{ +} + +void VirtualMessage::updateIsRead() +{ +} + +} +} +} diff --git a/src/platform/API/Messaging/VirtualMessage.h b/src/platform/API/Messaging/VirtualMessage.h new file mode 100755 index 0000000..bab4272 --- /dev/null +++ b/src/platform/API/Messaging/VirtualMessage.h @@ -0,0 +1,88 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file VirtualMessage.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef IVIRTUALMESSAGE_H +#define IVIRTUALMESSAGE_H + +#include +#include +#include +#include "IMessage.h" +#include "Subject.h" +#include "CcRecipient.h" +#include "BccRecipient.h" +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +#include "Attachments.h" +#endif +#include "CallbackNumber.h" +#include "ValidityPeriodHours.h" + +namespace TizenApis { +namespace Api { +namespace Messaging { + +//-------------------------------------------------------------------------- + +class VirtualMessage; +typedef DPL::SharedPtr VirtualMessagePtr; + +class VirtualMessage : + public IMessage, + public CcRecipient, + public BccRecipient +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + , + public Attachments +#endif +{ + public: + VirtualMessage(); + + virtual ~VirtualMessage(); + + int send(); + + void sendCancel(int handle); + + void update(bool draftsOnly = false); + + void readAllData(); + + void moveToFolder(const FolderType newFolder); + + void moveToFolder(const std::string& newFolder); + + void copyToFolder(const FolderType newFolder); + + void copyToFolder(const std::string& newFolder); + + void remove(); + + void updateIsRead(); +}; +} +} +} +#endif diff --git a/src/platform/API/Messaging/config.cmake b/src/platform/API/Messaging/config.cmake new file mode 100755 index 0000000..ea40b32 --- /dev/null +++ b/src/platform/API/Messaging/config.cmake @@ -0,0 +1,56 @@ +get_current_path() +set(SRCS_PLATFORM_API_MESSAGING + ${CURRENT_PATH}/IMessagingServiceManager.cpp + ${CURRENT_PATH}/IMessagingService.cpp + ${CURRENT_PATH}/MessagingFactory.cpp + +# ${CURRENT_PATH}/Attachments.cpp +# ${CURRENT_PATH}/IAttachment.cpp +# ${CURRENT_PATH}/AttachmentFactory.cpp + ${CURRENT_PATH}/BccRecipient.cpp + ${CURRENT_PATH}/Body.cpp + ${CURRENT_PATH}/CcRecipient.cpp + ${CURRENT_PATH}/From.cpp + ${CURRENT_PATH}/IBinarySms.cpp + ${CURRENT_PATH}/IEmail.cpp + ${CURRENT_PATH}/IMessage.cpp + ${CURRENT_PATH}/IMessaging.cpp + ${CURRENT_PATH}/IMms.cpp + ${CURRENT_PATH}/MmsSlide.cpp + ${CURRENT_PATH}/MmsSlides.cpp + ${CURRENT_PATH}/MmsSlideProperty.cpp + ${CURRENT_PATH}/ISms.cpp + ${CURRENT_PATH}/MessageFactory.cpp + ${CURRENT_PATH}/Recipient.cpp + ${CURRENT_PATH}/Subject.cpp + ${CURRENT_PATH}/ToRecipient.cpp + ${CURRENT_PATH}/ReqReceiverMessage.cpp + ${CURRENT_PATH}/EmailAccountInfo.cpp + ${CURRENT_PATH}/IEmailAccount.cpp + ${CURRENT_PATH}/SourceAddress.cpp + ${CURRENT_PATH}/CallbackNumber.cpp + ${CURRENT_PATH}/ValidityPeriodHours.cpp + ${CURRENT_PATH}/MessagePriority.cpp + ${CURRENT_PATH}/VirtualMessage.cpp + ${CURRENT_PATH}/EventMessageReceived.cpp + ${CURRENT_PATH}/EmitterMessageReceived.cpp + ${CURRENT_PATH}/EmitterConversationReceived.cpp + ${CURRENT_PATH}/EmitterFolderReceived.cpp + ${CURRENT_PATH}/MessageFilterValidatorFactory.cpp + ${CURRENT_PATH}/MessageFilterValidator.cpp + ${CURRENT_PATH}/ConversationFilterValidatorFactory.cpp + ${CURRENT_PATH}/ConversationFilterValidator.cpp + ${CURRENT_PATH}/FolderFilterValidatorFactory.cpp + ${CURRENT_PATH}/FolderFilterValidator.cpp + ${CURRENT_PATH}/StorageChangesMessageFilterValidatorFactory.cpp + ${CURRENT_PATH}/StorageChangesMessageFilterValidator.cpp + ${CURRENT_PATH}/StorageChangesMessageGenerator.cpp + ${CURRENT_PATH}/StorageChangesConversationFilterValidatorFactory.cpp + ${CURRENT_PATH}/StorageChangesConversationFilterValidator.cpp + ${CURRENT_PATH}/StorageChangesConversationGenerator.cpp + ${CURRENT_PATH}/StorageChangesFolderFilterValidatorFactory.cpp + ${CURRENT_PATH}/StorageChangesFolderFilterValidator.cpp + ${CURRENT_PATH}/StorageChangesFolderGenerator.cpp + + PARENT_SCOPE +) diff --git a/src/platform/API/Messaging/log.h b/src/platform/API/Messaging/log.h new file mode 100755 index 0000000..eee9e42 --- /dev/null +++ b/src/platform/API/Messaging/log.h @@ -0,0 +1,29 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * log.h + * + * Created on: 2011. 11. 25. + * Author: sangtai + */ + +#ifndef LOG_H_ +#define LOG_H_ + +#define MsgLogError(ARG) LogError("\u001B[0;31m" << ARG << "\u001B[0;39m") +#define MsgLogWanning(ARG) LogError("\u001B[1;33m" << ARG << "\u001B[0;39m") + +#endif /* LOG_H_ */ diff --git a/src/platform/API/NFC/EventNFC.h b/src/platform/API/NFC/EventNFC.h new file mode 100755 index 0000000..48d8763 --- /dev/null +++ b/src/platform/API/NFC/EventNFC.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WRTPLUGINS_API_NFC_EVENT_NFC_H_ +#define WRTPLUGINS_API_NFC_EVENT_NFC_H_ + +#include + +namespace TizenApis { +namespace Api { +namespace NFC { + +template +class EventNFCTemplate : public WrtDeviceApis::Commons::IEvent +{ +protected: + bool result; +public: + void setResult(const bool value) {result = value;} + bool getResult() const {return result;} + + EventNFCTemplate() { } +}; + + +} // NFC +} // Api +} // TizenApis + +#endif //WRTPLUGINS_API_NFC_EVENT_NFC_H_ \ No newline at end of file diff --git a/src/platform/API/NFC/EventNFCChanged.h b/src/platform/API/NFC/EventNFCChanged.h new file mode 100755 index 0000000..5fceaf6 --- /dev/null +++ b/src/platform/API/NFC/EventNFCChanged.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WRTPLUGINS_API_NFC_EVENT_NFC_CHANGED_H_ +#define WRTPLUGINS_API_NFC_EVENT_NFC_CHANGED_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace NFC { +enum EventNFCType { + NFC_TAG_TYPE, + NFC_TAG_MIFARE_CLASSIC_TYPE, + NFC_TAG_MIFARE_ULTRA_TYPE, + NFC_TARGET_TYPE +}; +enum EventNFCStatus { + NFC_ATTATCHED, + NFC_DETATCHED +}; +enum nfcSeEventType { + NFC_SE_EVENTTYPE_START_TRANSACTION, + NFC_SE_EVENTTYPE_END_TRANSACTION, + NFC_SE_EVENTTYPE_CONNECTIVITY, + NFC_SE_EVENTTYPE_FIELD_ON, + NFC_SE_EVENTTYPE_FIELD_OFF +}; + +class EventNFCChanged : public WrtDeviceApis::Commons::ListenerEvent +{ +private: + void *m_props; + void *privNFCManager; + EventNFCType m_type; + EventNFCStatus m_status; +public: + void *getNFCProperties() { return m_props; } + void setNFCProperties(void *props) { m_props = props; } + void setPrivateNFCManagerPtr(void* priv) {privNFCManager = priv;} + void *getPrivateNFCManagerPtr() {return privNFCManager;} + EventNFCType getNFCType() const {return m_type;} + void setNFCType(const EventNFCType type) {m_type = type;} + EventNFCStatus getNFCStatus() const {return m_status;} + void setNFCStatus(const EventNFCStatus type) {m_status = type;} + EventNFCChanged() {} +}; + +class EventNFCChangedNdef : public WrtDeviceApis::Commons::ListenerEvent +{ +private: + std::vector rawData; +public: + void setReadNdefResult(std::vector result) {rawData = result;} + std::vector getReadNdefResult() {return rawData;} + EventNFCChangedNdef(){ } +}; + +class EventNFCChangedSeEvent : public WrtDeviceApis::Commons::ListenerEvent +{ +private: + nfcSeEventType eventType; +public: + void setSeEvent(nfcSeEventType event) {eventType = event;} + nfcSeEventType getSeEvent() {return eventType;} + EventNFCChangedSeEvent(){ } +}; + +typedef DPL::SharedPtr EventNFCChangedPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter EventNFCChangedEmitter; +typedef DPL::SharedPtr EventNFCChangedEmitterPtr; + +typedef DPL::SharedPtr EventNFCChangedNdefPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter EventNFCChangedNdefEmitter; +typedef DPL::SharedPtr EventNFCChangedNdefEmitterPtr; + +typedef DPL::SharedPtr EventNFCChangedSeEventPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter EventNFCChangedSeEventEmitter; +typedef DPL::SharedPtr EventNFCChangedSeEventEmitterPtr; + +} // NFC +} // Api +} // TizenApis + +#endif //WRTPLUGINS_API_NFC_EVENT_NFC_CHANGED_H_ \ No newline at end of file diff --git a/src/platform/API/NFC/EventTagAction.h b/src/platform/API/NFC/EventTagAction.h new file mode 100755 index 0000000..eb2410a --- /dev/null +++ b/src/platform/API/NFC/EventTagAction.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef WRTPLUGINS_API_NFC_EVENT_TAG_ACTION_H_ +#define WRTPLUGINS_API_NFC_EVENT_TAG_ACTION_H_ + +#include +#include "EventNFC.h" +#include + +namespace TizenApis { +namespace Api { +namespace NFC { + +template +class EventTagAction : public EventNFCTemplate +{ +protected: + void *messageHandle; + void setNdefMessageHandle(void *handle) { messageHandle = handle; } + void *getNdefMessageHandle() { return messageHandle; } +public: + EventTagAction() { } +}; + +class EventTagActionRead : public EventNFCTemplate +{ +public: + void setReadNdefResult(std::vector result) {rawData = result;} + std::vector getReadNdefResult() {return rawData;} + EventTagActionRead(){ } +private: + std::vector rawData; + +}; + +class EventTagActionWrite : public EventTagAction +{ +public: + void writeNdef(void *handle) {setNdefMessageHandle(handle);} + void *getNdefForWriting() {return getNdefMessageHandle();} + EventTagActionWrite(){ } +}; + +class EventTagActionTransceive : public EventNFCTemplate +{ +private: + std::vector transceiveBuffer; +public: + void setTransceiveBuffer(const std::vector data) {transceiveBuffer = data;} + std::vector getTransceiveBuffer() const {return transceiveBuffer;} + int getTransceiveBufferSize() const {return transceiveBuffer.size();} + void transceive(const std::vector data) {setTransceiveBuffer(data);} + EventTagActionTransceive() { } +}; + +class EventTagActionFormat : public EventNFCTemplate +{ +private: + std::vector m_key; + +public: + void format(const std::vector key) {m_key = key;} + std::vector getKey() {return m_key;} + int getKeySize() const {return m_key.size();} + EventTagActionFormat() { } +}; + +typedef DPL::SharedPtr EventTagActionReadPtr; +typedef DPL::SharedPtr EventTagActionWritePtr; +typedef DPL::SharedPtr EventTagActionTransceivePtr; +typedef DPL::SharedPtr EventTagActionFormatPtr; +} // NFC +} // Api +} // TizenApis + +#endif //WRTPLUGINS_API_NFC_EVENT_TAG_ACTION_H_ diff --git a/src/platform/API/NFC/EventTagMifareClassicAction.h b/src/platform/API/NFC/EventTagMifareClassicAction.h new file mode 100755 index 0000000..15f18be --- /dev/null +++ b/src/platform/API/NFC/EventTagMifareClassicAction.h @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef WRTPLUGINS_API_NFC_EVENT_TAGMIFARECLASSIC_ACTION_H_ +#define WRTPLUGINS_API_NFC_EVENT_TAGMIFARECLASSIC_ACTION_H_ + +#include +#include "EventNFC.h" +#include + +namespace TizenApis { +namespace Api { +namespace NFC { + +template +class EventTagMifareClassicAuthenticate : public EventNFCTemplate +{ +protected: + std::vector key; + int sectorIndex; + void setKey(const std::vector &keyValue) {key = keyValue;} + void setSectorIndex(const int index) {sectorIndex = index;} +public: + std::vector getKey() const {return key;} + int getSectorIndex() const {return sectorIndex;} + EventTagMifareClassicAuthenticate() { } +}; + +class EventTagMifareClassicAuthenticateWithKeyA : public EventTagMifareClassicAuthenticate +{ +public: + EventTagMifareClassicAuthenticateWithKeyA(const std::vector &keyValue, const int index) { + setKey(keyValue); + setSectorIndex(index); + } +}; + +class EventTagMifareClassicAuthenticateWithKeyB : public EventTagMifareClassicAuthenticate +{ +public: + EventTagMifareClassicAuthenticateWithKeyB(const std::vector &keyValue, const int index) { + setKey(keyValue); + setSectorIndex(index); + } +}; + +template +class EventTagMifareClassicBlockAction : public EventNFCTemplate +{ + protected: + int blockIndex; + void setBlockIndex(const int index) {blockIndex = index;} + public: + EventTagMifareClassicBlockAction() {} + int getIndex() const {return blockIndex;} +}; + +class EventTagMifareClassicReadBlock : public EventTagMifareClassicBlockAction +{ + private: + std::vector blockData; + public: + EventTagMifareClassicReadBlock(const int index) {setBlockIndex(index);} + void setBlockData(const std::vector data) {blockData = data;} + std::vector getBlockData() const {return blockData;} +}; + +class EventTagMifareClassicWriteBlock : public EventTagMifareClassicBlockAction +{ + private: + std::vector blockData; + public: + EventTagMifareClassicWriteBlock(const int index, const std::vector data) : blockData(data) {setBlockIndex(index);} + std::vector getBlockData() const {return blockData;} +}; + +class EventTagMifareClassicIncrementBlockValue : public EventTagMifareClassicBlockAction +{ + private: + int blockValue; + public: + EventTagMifareClassicIncrementBlockValue(const int index, const int value) : blockValue(value) {setBlockIndex(index);} + int getValue() const {return blockValue;} +}; + +class EventTagMifareClassicDecrementBlockValue : public EventTagMifareClassicBlockAction +{ + private: + int blockValue; + public: + EventTagMifareClassicDecrementBlockValue(const int index, const int value) : blockValue(value) {setBlockIndex(index);} + int getValue() const {return blockValue;} +}; + +class EventTagMifareClassicTransfer : public EventTagMifareClassicBlockAction +{ + public: + EventTagMifareClassicTransfer(const int index) {setBlockIndex(index);} +}; + +class EventTagMifareClassicRestore : public EventTagMifareClassicBlockAction +{ + public: + EventTagMifareClassicRestore(const int index) {setBlockIndex(index);} +}; + +typedef DPL::SharedPtr EventTagMifareClassicAuthenticateWithKeyAPtr; +typedef DPL::SharedPtr EventTagMifareClassicAuthenticateWithKeyBPtr; +typedef DPL::SharedPtr EventTagMifareClassicReadBlockPtr; +typedef DPL::SharedPtr EventTagMifareClassicWriteBlockPtr; +typedef DPL::SharedPtr EventTagMifareClassicIncrementBlockValuePtr; +typedef DPL::SharedPtr EventTagMifareClassicDecrementBlockValuePtr; +typedef DPL::SharedPtr EventTagMifareClassicTransferPtr; +typedef DPL::SharedPtr EventTagMifareClassicRestorePtr; + +} // NFC +} // Api +} // TizenApis + +#endif //WRTPLUGINS_API_NFC_EVENT_TAGMIFARECLASSIC_ACTION_H_ diff --git a/src/platform/API/NFC/EventTagMifareUltraAction.h b/src/platform/API/NFC/EventTagMifareUltraAction.h new file mode 100755 index 0000000..c2527cd --- /dev/null +++ b/src/platform/API/NFC/EventTagMifareUltraAction.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef WRTPLUGINS_API_NFC_EVENT_TAGMIFAREULTRA_ACTION_H_ +#define WRTPLUGINS_API_NFC_EVENT_TAGMIFAREULTRA_ACTION_H_ + +#include +#include "EventNFC.h" +#include + +namespace TizenApis { +namespace Api { +namespace NFC { + +template +class EventTagMifareUltraPageAction : public EventNFCTemplate +{ + protected: + int pageIndex; + std::vector pageData; + void setIndex(const int index) {pageIndex = index;} + void setPage(const std::vector page) {pageData = page;} + const std::vector getPage() const {return pageData;} + public: + EventTagMifareUltraPageAction() {} + +}; +class EventTagMifareUltraReadPage : public EventTagMifareUltraPageAction +{ + public: + EventTagMifareUltraReadPage(const int index) {setIndex(index);} + int getIndex() const {return pageIndex;} + void setReadPageResult(const std::vector page) {setPage(page);} + const std::vector getReadPageResult() const {return getPage();} +}; + +class EventTagMifareUltraWritePage : public EventTagMifareUltraPageAction +{ + public: + EventTagMifareUltraWritePage(const int index, const std::vector data) + { + setIndex(index); + setPage(data); + } + int getIndex() const {return pageIndex;} + std::vector getPageForWriting() const {return getPage();} +}; + + +typedef DPL::SharedPtr EventTagMifareUltraReadPagePtr; +typedef DPL::SharedPtr EventTagMifareUltraWritePagePtr; + +} // NFC +} // Api +} // TizenApis + +#endif //WRTPLUGINS_API_NFC_EVENT_TAGMIFAREULTRA_ACTION_H_ \ No newline at end of file diff --git a/src/platform/API/NFC/EventTargetAction.h b/src/platform/API/NFC/EventTargetAction.h new file mode 100755 index 0000000..7beee88 --- /dev/null +++ b/src/platform/API/NFC/EventTargetAction.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef WRTPLUGINS_API_NFC_EVENT_TARGET_ACTION_H_ +#define WRTPLUGINS_API_NFC_EVENT_TARGET_ACTION_H_ + +#include +#include +#include +#include +#include "EventNFC.h" + +namespace TizenApis { +namespace Api { +namespace NFC { + +class EventTargetActionReceive : public WrtDeviceApis::Commons::ListenerEvent +{ + +public: + void setReadNdefResult(std::vector ndefResult) {rawData = ndefResult;} + std::vector getReadNdefResult() {return rawData;} + EventTargetActionReceive(){ } +private: + std::vector rawData; + +}; + +class EventTargetActionSend : public EventNFCTemplate +{ +public: + void *getMessageForSending() {return message;} + EventTargetActionSend(void *handle) :message(handle){ } +private: + void *message; +}; + +typedef DPL::SharedPtr EventTargetActionReceivePtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter EventTargetActionReceiveEmitter; +typedef DPL::SharedPtr EventTargetActionReceiveEmitterPtr; + +typedef DPL::SharedPtr EventTargetActionSendPtr; + +} // NFC +} // Api +} // TizenApis + +#endif //WRTPLUGINS_API_NFC_EVENT_TARGET_ACTION_H_ diff --git a/src/platform/API/NFC/INFCManager.cpp b/src/platform/API/NFC/INFCManager.cpp new file mode 100755 index 0000000..d54c77f --- /dev/null +++ b/src/platform/API/NFC/INFCManager.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "INFCManager.h" + +namespace TizenApis { +namespace Api { +namespace NFC { + +using namespace WrtDeviceApis::Commons; + +INFCManager::INFCManager() { +} + +INFCManager::~INFCManager() { +} + +} +} +} diff --git a/src/platform/API/NFC/INFCManager.h b/src/platform/API/NFC/INFCManager.h new file mode 100755 index 0000000..338d46d --- /dev/null +++ b/src/platform/API/NFC/INFCManager.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _ABSTRACT_LAYER_INFCMANAGER_H_ +#define _ABSTRACT_LAYER_INFCMANAGER_H_ + +#include +#include +#include +#include "EventNFCChanged.h" +#include "TagFilter.h" + +namespace TizenApis { +namespace Api { +namespace NFC { + +class INFCManager +{ + public: + + virtual ~INFCManager(); + virtual int setTagListener(const EventNFCChangedEmitterPtr& emitter, TagFilterPtr filter, void *managerPriv) = 0; + virtual void unsetTagListener() = 0; + virtual int setPeerListener(const EventNFCChangedEmitterPtr& emitter, void *managerPriv) = 0; + virtual void unsetPeerListener() = 0; + virtual int setNDEFListener(const EventNFCChangedNdefEmitterPtr& emitter) = 0; + virtual void unsetNDEFListener() = 0; + virtual int setSEEventListener(const EventNFCChangedSeEventEmitterPtr& emitter) = 0; + virtual void unsetSEEventListener() = 0; + + virtual void NFCHasDetected(void *props, EventNFCType type) = 0; + virtual void NDEFHasDetected(std::vector data) = 0; + virtual void SeEventHasDetected(nfcSeEventType event) = 0; + + virtual void *getCachedMessage() = 0; + virtual bool isValidHandle(void * handle) = 0; + virtual void updateCurrentHandle(void *handle) = 0; +protected: + INFCManager(); + void *curHandle; +}; + +typedef DPL::SharedPtr INFCManagerPtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_INFCMANAGER_H_ */ diff --git a/src/platform/API/NFC/INFCTag.cpp b/src/platform/API/NFC/INFCTag.cpp new file mode 100755 index 0000000..d069e7c --- /dev/null +++ b/src/platform/API/NFC/INFCTag.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "INFCTag.h" + +namespace TizenApis { +namespace Api { +namespace NFC { + +using namespace WrtDeviceApis::Commons; + +INFCTag::INFCTag() : + EventRequestReceiver(ThreadEnum::NFC_THREAD), + EventRequestReceiver(ThreadEnum::NFC_THREAD), + EventRequestReceiver(ThreadEnum::NFC_THREAD), + EventRequestReceiver(ThreadEnum::NFC_THREAD){ +} + +INFCTag::~INFCTag() { +} + +} +} +} diff --git a/src/platform/API/NFC/INFCTag.h b/src/platform/API/NFC/INFCTag.h new file mode 100755 index 0000000..25f30ca --- /dev/null +++ b/src/platform/API/NFC/INFCTag.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _ABSTRACT_LAYER_NFCTAG_H_ +#define _ABSTRACT_LAYER_NFCTAG_H_ + +#include +#include +#include +#include "EventTagAction.h" +#include "NFCTagProperties.h" + +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { +namespace Api { +namespace NFC { + + enum nfcTagType { + NFC_TAGTYPE_GENERIC_PICC = 0x00, + NFC_TAGTYPE_ISO14443_A_PICC = 0x01, + NFC_TAGTYPE_ISO14443_4A_PICC = 0x02, + NFC_TAGTYPE_ISO14443_3A_PICC = 0x03, + NFC_TAGTYPE_MIFARE_MINI_PICC = 0x04, + NFC_TAGTYPE_MIFARE_1K_PICC = 0x05, + NFC_TAGTYPE_MIFARE_4K_PICC = 0x06, + NFC_TAGTYPE_MIFARE_ULTRA_PICC = 0x07, + NFC_TAGTYPE_MIFARE_DESFIRE_PICC = 0x08, + NFC_TAGTYPE_ISO14443_B_PICC = 0x09, + NFC_TAGTYPE_ISO14443_4B_PICC = 0x0a, + NFC_TAGTYPE_ISO14443_BPRIME_PICC = 0x0b, + NFC_TAGTYPE_FELICA_PICC = 0x0c, + NFC_TAGTYPE_JEWEL_PICC = 0x0d, + NFC_TAGTYPE_ISO15693_PICC = 0x0e, + NFC_TAGTYPE_UNKNOWN_TARGET = 0xff + }; + +class INFCTag : + public EventRequestReceiver, + public EventRequestReceiver, + public EventRequestReceiver, + public EventRequestReceiver +{ + public: + + + virtual ~INFCTag(); + virtual void *getHandle() = 0; + virtual nfcTagType getTagType() = 0; + virtual bool isNDEFSupport() = 0; + virtual long getNdefSize() = 0; + virtual std::vector getProperties() = 0; + virtual void readNdef(const EventTagActionReadPtr& event) = 0; + virtual void writeNdef(const EventTagActionWritePtr& event) = 0; + virtual void transceive(const EventTagActionTransceivePtr& event) = 0; + virtual void format(const EventTagActionFormatPtr& event) = 0; + + virtual void readNdefManualAnswer(int result , std::vector data) = 0; + virtual void writeNdefManualAnswer(int result) = 0; + virtual void transceiveManualAnswer(int result , std::vector data) = 0; + virtual void formatManualAnswer(int result) = 0; + + virtual void setPrivateNFCManagerPtr(void* priv) {privNFCManager = priv;} + virtual void *getPrivateNFCManagerPtr() {return privNFCManager;} + protected: + INFCTag(); + virtual void OnRequestReceived(const EventTagActionReadPtr& event) = 0; + virtual void OnRequestReceived(const EventTagActionWritePtr& event) = 0; + virtual void OnRequestReceived(const EventTagActionTransceivePtr& event) = 0; + virtual void OnRequestReceived(const EventTagActionFormatPtr& event) = 0; + + void *privNFCManager; +}; + +typedef DPL::SharedPtr INFCTagPtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_NFCTAG_H_ */ diff --git a/src/platform/API/NFC/INFCTagMifareClassic.cpp b/src/platform/API/NFC/INFCTagMifareClassic.cpp new file mode 100755 index 0000000..cd01edf --- /dev/null +++ b/src/platform/API/NFC/INFCTagMifareClassic.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "INFCTagMifareClassic.h" + +namespace TizenApis { +namespace Api { +namespace NFC { +using namespace WrtDeviceApis::Commons; + +INFCTagMifareClassic::INFCTagMifareClassic() : Platform::NFC::NFCTag(NULL), + EventRequestReceiver(ThreadEnum::NFC_THREAD), + EventRequestReceiver(ThreadEnum::NFC_THREAD), + EventRequestReceiver(ThreadEnum::NFC_THREAD), + EventRequestReceiver(ThreadEnum::NFC_THREAD), + EventRequestReceiver(ThreadEnum::NFC_THREAD), + EventRequestReceiver(ThreadEnum::NFC_THREAD), + EventRequestReceiver(ThreadEnum::NFC_THREAD), + EventRequestReceiver(ThreadEnum::NFC_THREAD) { + +} + +INFCTagMifareClassic::~INFCTagMifareClassic() { +} + +} +} +} diff --git a/src/platform/API/NFC/INFCTagMifareClassic.h b/src/platform/API/NFC/INFCTagMifareClassic.h new file mode 100755 index 0000000..e3f5bff --- /dev/null +++ b/src/platform/API/NFC/INFCTagMifareClassic.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _ABSTRACT_LAYER_NFCTAGMIFARECLASSIC_H_ +#define _ABSTRACT_LAYER_NFCTAGMIFARECLASSIC_H_ + +#include +#include +#include +#include "EventTagMifareClassicAction.h" +#include + +namespace TizenApis { +namespace Api { +namespace NFC { +using namespace WrtDeviceApis::Commons; + +class INFCTagMifareClassic : public Platform::NFC::NFCTag, + public EventRequestReceiver, + public EventRequestReceiver, + public EventRequestReceiver, + public EventRequestReceiver, + public EventRequestReceiver, + public EventRequestReceiver, + public EventRequestReceiver, + public EventRequestReceiver +{ + public: + + + virtual ~INFCTagMifareClassic(); + virtual void authenticateWithKeyA(const EventTagMifareClassicAuthenticateWithKeyAPtr& event) = 0; + virtual void authenticateWithKeyB(const EventTagMifareClassicAuthenticateWithKeyBPtr& event) = 0; + virtual void readBlock(const EventTagMifareClassicReadBlockPtr& event) = 0; + virtual void writeBlock(const EventTagMifareClassicWriteBlockPtr& event) = 0; + virtual void incrementBlockValue(const EventTagMifareClassicIncrementBlockValuePtr& event) = 0; + virtual void decrementBlockValue(const EventTagMifareClassicDecrementBlockValuePtr& event) = 0; + virtual void transfer(const EventTagMifareClassicTransferPtr& event) = 0; + virtual void restore(const EventTagMifareClassicRestorePtr& event) = 0; + virtual void authenticateWithKeyAManualAnswer(int result) = 0; + virtual void authenticateWithKeyBManualAnswer(int result) = 0; + virtual void readBlockManualAnswer(int result , std::vector data) = 0; + virtual void writeBlockManualAnswer(int result ) = 0; + virtual void incrementBlockValueManualAnswer(int result) = 0; + virtual void decrementBlockValueManualAnswer(int result ) = 0; + virtual void transferManualAnswer(int result ) = 0; + virtual void restoreManualAnswer(int result ) = 0; + protected: + INFCTagMifareClassic(); + virtual void OnRequestReceived(const EventTagMifareClassicAuthenticateWithKeyAPtr& event) = 0; + virtual void OnRequestReceived(const EventTagMifareClassicAuthenticateWithKeyBPtr& event) = 0; + virtual void OnRequestReceived(const EventTagMifareClassicReadBlockPtr& event) = 0; + virtual void OnRequestReceived(const EventTagMifareClassicWriteBlockPtr& event) = 0; + virtual void OnRequestReceived(const EventTagMifareClassicIncrementBlockValuePtr& event) = 0; + virtual void OnRequestReceived(const EventTagMifareClassicDecrementBlockValuePtr& event) = 0; + virtual void OnRequestReceived(const EventTagMifareClassicTransferPtr& event) = 0; + virtual void OnRequestReceived(const EventTagMifareClassicRestorePtr& event) = 0; +}; + +typedef DPL::SharedPtr INFCTagMifareClassicPtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_NFCTAGMIFARECLASSIC_H_ */ diff --git a/src/platform/API/NFC/INFCTagMifareUltra.cpp b/src/platform/API/NFC/INFCTagMifareUltra.cpp new file mode 100755 index 0000000..a725038 --- /dev/null +++ b/src/platform/API/NFC/INFCTagMifareUltra.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "INFCTagMifareUltra.h" + +namespace TizenApis { +namespace Api { +namespace NFC { +using namespace WrtDeviceApis::Commons; + +INFCTagMifareUltra::INFCTagMifareUltra() : Platform::NFC::NFCTag(NULL), + EventRequestReceiver(ThreadEnum::NFC_THREAD), + EventRequestReceiver(ThreadEnum::NFC_THREAD) { + +} + +INFCTagMifareUltra::~INFCTagMifareUltra() { +} + +} +} +} diff --git a/src/platform/API/NFC/INFCTagMifareUltra.h b/src/platform/API/NFC/INFCTagMifareUltra.h new file mode 100755 index 0000000..cbebcac --- /dev/null +++ b/src/platform/API/NFC/INFCTagMifareUltra.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _ABSTRACT_LAYER_NFCTTAGMIFAREULTRA_H_ +#define _ABSTRACT_LAYER_NFCTTAGMIFAREULTRA_H_ + +#include +#include +#include +#include "EventTagMifareUltraAction.h" +#include + +namespace TizenApis { +namespace Api { +namespace NFC { +using namespace WrtDeviceApis::Commons; + +class INFCTagMifareUltra : public Platform::NFC::NFCTag, + public EventRequestReceiver, + public EventRequestReceiver +{ + public: + + + virtual ~INFCTagMifareUltra(); + virtual void readPage(const EventTagMifareUltraReadPagePtr& event) = 0; + virtual void writePage(const EventTagMifareUltraWritePagePtr& event) = 0; + virtual void readPageManualAnswer(int result , std::vector data) = 0; + virtual void writePageManualAnswer(int result) = 0; + protected: + INFCTagMifareUltra(); + virtual void OnRequestReceived(const EventTagMifareUltraReadPagePtr& event) = 0; + virtual void OnRequestReceived(const EventTagMifareUltraWritePagePtr& event) = 0; +}; + +typedef DPL::SharedPtr INFCTagMifareUltraPtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_NFCTTAGMIFAREULTRA_H_ */ diff --git a/src/platform/API/NFC/INFCTarget.cpp b/src/platform/API/NFC/INFCTarget.cpp new file mode 100755 index 0000000..0482db0 --- /dev/null +++ b/src/platform/API/NFC/INFCTarget.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "INFCTarget.h" + +namespace TizenApis { +namespace Api { +namespace NFC { + +using namespace WrtDeviceApis::Commons; + +INFCTarget::INFCTarget() : EventRequestReceiver(ThreadEnum::NFC_THREAD) { +} + +INFCTarget::~INFCTarget() { +} + +} +} +} diff --git a/src/platform/API/NFC/INFCTarget.h b/src/platform/API/NFC/INFCTarget.h new file mode 100755 index 0000000..49f68ac --- /dev/null +++ b/src/platform/API/NFC/INFCTarget.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _ABSTRACT_LAYER_NFCTARGET_H_ +#define _ABSTRACT_LAYER_NFCTARGET_H_ + +#include +#include +#include "EventTargetAction.h" + +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { +namespace Api { +namespace NFC { + + +class INFCTarget : public EventRequestReceiver +{ + public: + + + virtual ~INFCTarget(); + virtual void *getHandle() = 0; + virtual void setReceiveNDEFListener(const EventTargetActionReceiveEmitterPtr& event) = 0; + virtual void receiveNdef(std::vectormessageData) = 0; + virtual void unsetReceiveNDEFListener() = 0; + virtual void sendNDEF(const EventTargetActionSendPtr& event) = 0; + virtual void sendNDEFManualAnswer(unsigned int result) = 0; + virtual void setPrivateNFCManagerPtr(void* priv) {privNFCManager = priv;} + virtual void *getPrivateNFCManagerPtr() {return privNFCManager;} + protected: + INFCTarget(); + virtual void OnRequestReceived(const EventTargetActionSendPtr& event) = 0; + void *privNFCManager; +}; + +typedef DPL::SharedPtr INFCTargetPtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_NFCTARGET_H_ */ diff --git a/src/platform/API/NFC/INdefMessage.h b/src/platform/API/NFC/INdefMessage.h new file mode 100755 index 0000000..71f90e3 --- /dev/null +++ b/src/platform/API/NFC/INdefMessage.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _ABSTRACT_LAYER_INDEFMESSAGE_H_ +#define _ABSTRACT_LAYER_INDEFMESSAGE_H_ + +#include +#include +#include "NdefRecordProperties.h" + +namespace TizenApis { +namespace Api { +namespace NFC { + +class INdefMessage +{ + public: + + INdefMessage() {} + virtual ~INdefMessage() {} + virtual void *getHandle() = 0; + virtual long getRecordCount() = 0; + virtual std::vector toByte()= 0; + virtual NdefRecordData getNDEFRecord(const long index) = 0; + virtual bool insertNDEFRecord(const long index, const void *recordHandle) = 0; + virtual bool appendNDEFRecord(const void *recordHandle) = 0; + virtual bool removeNDEFRecord(const long index) = 0; + +}; + +typedef DPL::SharedPtr INdefMessagePtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_INDEFMESSAGE_H_ */ diff --git a/src/platform/API/NFC/INdefRecord.h b/src/platform/API/NFC/INdefRecord.h new file mode 100755 index 0000000..ee02f01 --- /dev/null +++ b/src/platform/API/NFC/INdefRecord.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _ABSTRACT_LAYER_INDEFRECORD_H_ +#define _ABSTRACT_LAYER_INDEFRECORD_H_ + +#include +#include +#include "NdefRecordProperties.h" + + +namespace TizenApis { +namespace Api { +namespace NFC { + +class INdefRecord +{ + public: + INdefRecord() {} + virtual ~INdefRecord() {} + virtual void *getHandle() = 0; + virtual NdefRecordProperties getNDEFRecordProperties() = 0; + virtual std::vector getPayload() = 0; + virtual bool getText(char **text) = 0; + virtual bool getLangCode(char **landCode) = 0; + virtual bool getEncodeType(nfcTextEncodeUTF *encodeType) = 0; + virtual bool getUri(char **uri) = 0; + virtual bool getMimeType(char **mimeType) = 0; + protected: + +}; + +typedef DPL::SharedPtr INdefRecordPtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_INDEFRECORD_H_ */ diff --git a/src/platform/API/NFC/NFCFactory.cpp b/src/platform/API/NFC/NFCFactory.cpp new file mode 100755 index 0000000..a705d3c --- /dev/null +++ b/src/platform/API/NFC/NFCFactory.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "NFCFactory.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace NFC { + +INFCManagerPtr NFCFactory::createNFCManagerObject() { + return INFCManagerPtr( new Platform::NFC::NFCManager() ); +} + +INdefMessagePtr NFCFactory::createNDEFMessageObject() { + return INdefMessagePtr( new Platform::NFC::NdefMessage() ); +} + +INdefMessagePtr NFCFactory::createNDEFMessageObject(void *messageHandle) { + return INdefMessagePtr( new Platform::NFC::NdefMessage(messageHandle) ); +} + +INdefMessagePtr NFCFactory::createNDEFMessageObject(std::vector ndefRcords) { + return INdefMessagePtr( new Platform::NFC::NdefMessage(ndefRcords) ); +} + +INdefMessagePtr NFCFactory::createNDEFMessageObject(std::vector rawdata) { + return INdefMessagePtr( new Platform::NFC::NdefMessage(rawdata) ); +} + +INdefRecordPtr NFCFactory::createNDEFRecordObject(const NdefRecordProperties &ndefRecordProperties, std::vector payload) { + return INdefRecordPtr( new Platform::NFC::NdefRecord(ndefRecordProperties, payload) ); +} + +INdefRecordPtr NFCFactory::createNDEFRecordObject(const std::string &text, const std::string &langCode, const short encodeType) { + return INdefRecordPtr( new Platform::NFC::NdefRecord(text, langCode, encodeType) ); +} + +INdefRecordPtr NFCFactory::createNDEFRecordObject(const std::string &uri) { + return INdefRecordPtr( new Platform::NFC::NdefRecord(uri) ); +} + +INdefRecordPtr NFCFactory::createNDEFRecordObject(const std::string &mimeType, const std::vector data) { + return INdefRecordPtr( new Platform::NFC::NdefRecord(mimeType, data) ); +} + +INFCTagPtr NFCFactory::createNFCTagObject(void *tagHandle) { + return INFCTagPtr( new Platform::NFC::NFCTag(tagHandle)); +} + +INFCTagMifareClassicPtr NFCFactory::createNFCTagMifareClassicObject(void *tagHandle) { + return INFCTagMifareClassicPtr( new Platform::NFC::NFCTagMifareClassic(tagHandle)); +} + +INFCTagMifareUltraPtr NFCFactory::createNFCTagMifareUltraObject(void *tagHandle) { + return INFCTagMifareUltraPtr( new Platform::NFC::NFCTagMifareUltra(tagHandle)); +} + +INFCTargetPtr NFCFactory::createNFCTargetObject(void *targetHandle) { + return INFCTargetPtr( new Platform::NFC::NFCTarget(targetHandle)); +} + +NFCFactory& NFCFactory::getInstance() { + static NFCFactory theInstance; + return theInstance; +} + +} +} +} diff --git a/src/platform/API/NFC/NFCFactory.h b/src/platform/API/NFC/NFCFactory.h new file mode 100755 index 0000000..6eed2b0 --- /dev/null +++ b/src/platform/API/NFC/NFCFactory.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef WRTPLUGINS_API_NFCFACTORY_H_ +#define WRTPLUGINS_API_NFCFACTORY_H_ + +#include +#include "INFCManager.h" +#include "INdefMessage.h" +#include "INdefRecord.h" +#include "INFCTag.h" +#include "INFCTagMifareClassic.h" +#include "INFCTagMifareUltra.h" +#include "INFCTarget.h" + +namespace TizenApis { +namespace Api { +namespace NFC { + +class NFCFactory : DPL::Noncopyable +{ +private: + /** + * Private constructor to provide singleton + */ + NFCFactory(){;} +public: + INFCManagerPtr createNFCManagerObject(); + INdefMessagePtr createNDEFMessageObject(); + INdefMessagePtr createNDEFMessageObject(void *messageHandle); + INdefMessagePtr createNDEFMessageObject(std::vector ndefRcords); + INdefMessagePtr createNDEFMessageObject(std::vector rawdata); + INdefRecordPtr createNDEFRecordObject(const NdefRecordProperties &ndefRecordProperties, std::vector payload); + INdefRecordPtr createNDEFRecordObject(const std::string &text, const std::string &langCode, const short encodeType); + INdefRecordPtr createNDEFRecordObject(const std::string &uri); + INdefRecordPtr createNDEFRecordObject(const std::string &mimeType, const std::vector data); + INFCTagPtr createNFCTagObject(void *tagHandle); + INFCTagMifareClassicPtr createNFCTagMifareClassicObject(void *tagHandle); + INFCTagMifareUltraPtr createNFCTagMifareUltraObject(void *tagHandle); + INFCTargetPtr createNFCTargetObject(void *targetHandle); + static NFCFactory& getInstance(); + +}; + +} +} +} + +#endif //WRTPLUGINS_API_NFCFACTORY_H_ + diff --git a/src/platform/API/NFC/NFCTagProperties.h b/src/platform/API/NFC/NFCTagProperties.h new file mode 100755 index 0000000..8cdeca4 --- /dev/null +++ b/src/platform/API/NFC/NFCTagProperties.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef WRTPLUGINS_API_NFC_NFCTAG_PROPERTIES_H_ +#define WRTPLUGINS_API_NFC_NFCTAG_PROPERTIES_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace NFC { + +struct NFCTagProperties +{ + std::string key ; + std::vector value ; + NFCTagProperties() + : key("") + { + } +}; + + +typedef DPL::SharedPtr NFCTagPropertiesPtr; + +} // NFC +} // Api +} // TizenApis + +#endif //WRTPLUGINS_API_NFC_NFCTAG_PROPERTIES_H_ \ No newline at end of file diff --git a/src/platform/API/NFC/NdefRecordProperties.h b/src/platform/API/NFC/NdefRecordProperties.h new file mode 100755 index 0000000..cfe52d1 --- /dev/null +++ b/src/platform/API/NFC/NdefRecordProperties.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef WRTPLUGINS_API_NFC_NDEFRECORD_PROPERTIES_H_ +#define WRTPLUGINS_API_NFC_NDEFRECORD_PROPERTIES_H_ + +#include +#include + +namespace TizenApis { +namespace Api { +namespace NFC { + +enum nfcTNF { + NFC_TNF_EMPTY = 0, + NFC_TNF_WELL_KNOWN = 1, + NFC_TNF_MIME_MEDIA = 2, + NFC_TNF_URI = 3, + NFC_TNF_EXTERNAL_RTD = 4, + NFC_TNF_UNKNOWN = 5, + NFC_TNF_UNCHAGNED = 6 +}; + +enum nfcTextEncodeUTF { + NFC_TEXT_ENCODE_UTF_8 = 0, + NFC_TEXT_ENCODE_UTF_16 = 1 +}; +struct NdefRecordProperties +{ + nfcTNF tnf; + std::vector typeName ; + std::vector id ; + NdefRecordProperties() + : tnf(NFC_TNF_EMPTY) + { + } +}; + +struct NdefRecordData +{ + NdefRecordProperties properties; + std::vector payload; + NdefRecordData() {} +}; + +typedef DPL::SharedPtr NdefRecordPropertiesPtr; + +} // NFC +} // Api +} // TizenApis + +#endif //WRTPLUGINS_API_NFC_NDEFRECORD_PROPERTIES_H_ \ No newline at end of file diff --git a/src/platform/API/NFC/TagFilter.cpp b/src/platform/API/NFC/TagFilter.cpp new file mode 100755 index 0000000..035f2c9 --- /dev/null +++ b/src/platform/API/NFC/TagFilter.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "TagFilter.h" + +namespace TizenApis { +namespace Api { +namespace NFC { + +TagFilter::TagFilter() +{ +} + +TagFilter::~TagFilter() +{ +} + +void TagFilter::addTagTypeValue(nfcTagType type){ + m_tagList.push_back(type); +} + +nfcTagType TagFilter::getFilterValue(int index){ + if (index >=0 && index < m_tagList.size()) + return m_tagList.at(index); + else + return NFC_TAGTYPE_UNKNOWN_TARGET; +} + +int TagFilter::getFilterSize(){ + return m_tagList.size(); +} + +} +} +} diff --git a/src/platform/API/NFC/TagFilter.h b/src/platform/API/NFC/TagFilter.h new file mode 100755 index 0000000..423400a --- /dev/null +++ b/src/platform/API/NFC/TagFilter.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _TIZEN10_NFC_TAG_FILTER_H_ +#define _TIZEN10_NFC_TAG_FILTER_H_ + +#include +#include +#include +#include +#include + +#include "INFCTag.h" + +namespace TizenApis { +namespace Api { +namespace NFC { + +class TagFilter +{ + public: + + typedef std::vector TagList; + + explicit TagFilter(); + virtual ~TagFilter(); + + void addTagTypeValue(nfcTagType type); + int getFilterSize(); + nfcTagType getFilterValue(int index); + private: + TagList m_tagList; +}; + +typedef DPL::SharedPtr TagFilterPtr; + +} +} +} +#endif //_TIZEN10_NFC_TAG_FILTER_H_ \ No newline at end of file diff --git a/src/platform/API/NFC/config.cmake b/src/platform/API/NFC/config.cmake new file mode 100755 index 0000000..da36668 --- /dev/null +++ b/src/platform/API/NFC/config.cmake @@ -0,0 +1,12 @@ +get_current_path() + +set(SRCS_PLATFORM_API_NFC + ${CURRENT_PATH}/NFCFactory.cpp + ${CURRENT_PATH}/INFCManager.cpp + ${CURRENT_PATH}/INFCTag.cpp + ${CURRENT_PATH}/INFCTagMifareClassic.cpp + ${CURRENT_PATH}/INFCTagMifareUltra.cpp + ${CURRENT_PATH}/TagFilter.cpp + ${CURRENT_PATH}/INFCTarget.cpp + PARENT_SCOPE +) diff --git a/src/platform/API/Systeminfo/BaseProperties.h b/src/platform/API/Systeminfo/BaseProperties.h new file mode 100755 index 0000000..df71153 --- /dev/null +++ b/src/platform/API/Systeminfo/BaseProperties.h @@ -0,0 +1,80 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_API_BASE_PROPERTIES_H_ +#define WRTPLUGINS_API_BASE_PROPERTIES_H_ + +#include +#include +#include +#include +#include +#include "standards/Tizen/Systeminfo/JSWifiNetworkInfo.h" +#include "standards/Tizen/Systeminfo/JSCellularNetworkInfo.h" +#include "standards/Tizen/Systeminfo/JSStorageInfo.h" +#include "standards/Tizen/Systeminfo/JSPowerInfo.h" +#include "standards/Tizen/Systeminfo/JSDisplayInfo.h" +#include "standards/Tizen/Systeminfo/JSDeviceInfo.h" +#include "standards/Tizen/Systeminfo/JSCpuInfo.h" + +#include "SysteminfoPropertyInfo.h" + +namespace TizenApis { +namespace Api { +namespace Systeminfo { + +struct WatchOption +{ + unsigned long timeout; + double highThreshold; + double lowThreshold; + std::string id; + + WatchOption () : + timeout(0), + highThreshold(0.0), + lowThreshold(0.0), + id("") + { + } +}; + +class BaseProperty +{ + public: + + explicit BaseProperty() + { + } + + virtual ~BaseProperty() + { + } + + virtual JSValueRef getValue(JSContextRef context) const = 0; + virtual const char* getProperty() const = 0; + virtual const int getWatchType() const = 0; +}; + +typedef DPL::SharedPtr BasePropertyPtr; + +} +} +} + +#endif diff --git a/src/platform/API/Systeminfo/EventGetSysteminfo.h b/src/platform/API/Systeminfo/EventGetSysteminfo.h new file mode 100755 index 0000000..ef0f07c --- /dev/null +++ b/src/platform/API/Systeminfo/EventGetSysteminfo.h @@ -0,0 +1,78 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_API_SYSTEMINFO_EVENT_GET_SYSTEMINFO_H_ +#define WRTPLUGINS_API_SYSTEMINFO_EVENT_GET_SYSTEMINFO_H_ + +#include +#include +#include +#include + +#include "ISysteminfo.h" + +namespace TizenApis { +namespace Api { +namespace Systeminfo { + +class EventGetSysteminfo; +typedef DPL::SharedPtr EventGetSysteminfoPtr; + +class EventGetSysteminfo : public WrtDeviceApis::Commons::IEvent +{ + private : + Api::Systeminfo::BasePropertyPtr m_BaseProperty; + JSValueRef m_value; + + public : + void setBasePropertyPtr(const BasePropertyPtr& baseProperty) { + m_BaseProperty = baseProperty; + } + + JSValueRef getValue() const { + return m_value; + } + + const char * getProperty() const { + return m_BaseProperty->getProperty(); + } + + void processGetValue() + { + LogDebug("enter"); + if (!m_BaseProperty) { + LogError("property is not set"); + setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::ConversionException); + } else { + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_callbackManager = DPL::StaticPointerCast(getPrivateData()); + if (!m_callbackManager) { + LogError("property is not set"); + setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::NullPointerException); + } else { + JSContextRef context = m_callbackManager->getContext(); + m_value = m_BaseProperty->getValue(context); + } + } + } +}; + +} +} +} + +#endif diff --git a/src/platform/API/Systeminfo/EventWatchSysteminfo.cpp b/src/platform/API/Systeminfo/EventWatchSysteminfo.cpp new file mode 100755 index 0000000..485af3f --- /dev/null +++ b/src/platform/API/Systeminfo/EventWatchSysteminfo.cpp @@ -0,0 +1,307 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include "EventWatchSysteminfo.h" +#include "Systeminfo/Systeminfo.h" + +namespace TizenApis { +namespace Api { +namespace Systeminfo { + +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace { + +static Eina_Bool timer_cb(void* data) +{ + LogDebug("enter"); + EventWatchSysteminfo *event = static_cast (data); + event->timeoutWatch(); + return ECORE_CALLBACK_RENEW; +} + +} + +DPL::Atomic EventWatchSysteminfo::m_uniqId = 1; + +EventWatchSysteminfo::EventWatchSysteminfo() : + m_id(m_uniqId), + m_canceled(false), + m_lastValue(NULL), + m_initTimer(NULL) +{ + ++m_uniqId; +} + +EventWatchSysteminfo::~EventWatchSysteminfo() +{ + LogDebug("destroy event data, id=" << m_id); +} + +void EventWatchSysteminfo::setWatchOption(const WatchOption& watchoption) { + m_WatchOption = watchoption; +} + +WatchOption EventWatchSysteminfo::getWatchOption() { + return m_WatchOption; +} + +JSCallbackManagerPtr EventWatchSysteminfo::getCallbackManager() { + return DPL::StaticPointerCast< JSCallbackManager >(getPrivateData()); +} + +BasePropertyPtr EventWatchSysteminfo::getBasePropertyPtr() { + return m_BaseProperty; +} + +void EventWatchSysteminfo::setSysteminfoPtr(void* SysteminfoPtr) { + m_Systeminfo = SysteminfoPtr; +} + +void EventWatchSysteminfo::setBasePropertyPtr(const BasePropertyPtr& baseProperty) { + m_BaseProperty = baseProperty; +} + +const char * EventWatchSysteminfo::getProperty() const { + return m_BaseProperty->getProperty(); +} + +const int EventWatchSysteminfo::getWatchType() const { + return m_BaseProperty->getWatchType(); +} + +void EventWatchSysteminfo::getWatchValue() +{ + LogDebug("enter"); + processGetValue(); +} + +int EventWatchSysteminfo::getId() const +{ + return m_id; +} + +JSValueRef EventWatchSysteminfo::getPropertyValue(JSContextRef context, JSValueRef value, std::string key) +{ + JSObjectRef object = NULL; + JSValueRef* exception = NULL; + JSStringRef propertyName = NULL; + + object = JSValueToObject(context, value, exception); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + + return JSObjectGetProperty(context, object, propertyName, exception); +} + +void EventWatchSysteminfo::processGetValue() +{ + LogDebug("thread=" << DPL::Thread::GetCurrentThread()); + if(!m_canceled) { + JSCallbackManagerPtr m_cbm = DPL::StaticPointerCast< JSCallbackManager >(getPrivateData()); + JSContextRef context = m_cbm->getContext(); + if(m_lastValue) { + JSValueRef* exception = NULL; + JSValueRef tmpValue = m_BaseProperty->getValue(context); + Converter converter(context); + if (NULL != tmpValue) { + LogDebug("watchType : " << m_BaseProperty->getWatchType()); + + if (m_BaseProperty->getWatchType() == 1) { + std::string key = "level"; + JSValueRef propertyLevel = getPropertyValue(context, tmpValue, key); + double level = JSValueToNumber(context, propertyLevel, exception); + propertyLevel = getPropertyValue(context, m_lastValue, key); + double prevLevel = JSValueToNumber(context, propertyLevel, exception); + + key = "isCharging"; + JSValueRef propertyCharging = getPropertyValue(context, tmpValue, key); + bool isCharging = JSValueToBoolean(context, propertyCharging); + propertyCharging = getPropertyValue(context, m_lastValue, key); + bool prevIsCharging = JSValueToBoolean(context, propertyCharging); + + if(level != prevLevel || isCharging != prevIsCharging) { + if (m_WatchOption.highThreshold > 0 || m_WatchOption.lowThreshold > 0) { + if (level > m_WatchOption.highThreshold || level < m_WatchOption.lowThreshold) { + m_cbm->callOnSuccess(tmpValue); + m_lastValue = tmpValue; + setTimer(); + } + } else { + m_cbm->callOnSuccess(tmpValue); + m_lastValue = tmpValue; + setTimer(); + } + } + } else if (m_BaseProperty->getWatchType() == 2) { + std::string key = "brightness"; + JSValueRef propertyBrightness = getPropertyValue(context, tmpValue, key); + double brightness = JSValueToNumber(context, propertyBrightness, exception); + propertyBrightness = getPropertyValue(context, m_lastValue, key); + double prevBrightness = JSValueToNumber(context, propertyBrightness, exception); + + if(brightness != prevBrightness) { + if (m_WatchOption.highThreshold > 0 || m_WatchOption.lowThreshold > 0) { + if (brightness > m_WatchOption.highThreshold || brightness < m_WatchOption.lowThreshold) { + m_cbm->callOnSuccess(tmpValue); + m_lastValue = tmpValue; + setTimer(); + } + } else { + m_cbm->callOnSuccess(tmpValue); + m_lastValue = tmpValue; + setTimer(); + } + } + } else if (m_BaseProperty->getWatchType() == 3) { + std::string key = "status"; + JSValueRef propertyStatus = getPropertyValue(context, tmpValue, key); + JSStringRef status = JSValueToStringCopy(context, propertyStatus, exception); + propertyStatus = getPropertyValue(context, m_lastValue, key); + JSStringRef prevStatus = JSValueToStringCopy(context, propertyStatus, exception); + + key = "ssid"; + JSValueRef propertySsid = getPropertyValue(context, tmpValue, key); + JSStringRef ssid = JSValueToStringCopy(context, propertySsid, exception); + propertySsid = getPropertyValue(context, m_lastValue, key); + JSStringRef prevSsid = JSValueToStringCopy(context, propertySsid, exception); + + key = "signalStrength"; + JSValueRef propertySignalStrength = getPropertyValue(context, tmpValue, key); + double signalStrength = JSValueToNumber(context, propertySignalStrength, exception); + propertySignalStrength = getPropertyValue(context, m_lastValue, key); + double prevSignalStrength = JSValueToNumber(context, propertySignalStrength, exception); + + if(!JSStringIsEqual(status,prevStatus) || !JSStringIsEqual(ssid,prevSsid) || signalStrength != prevSignalStrength) { + if (m_WatchOption.highThreshold > 0 || m_WatchOption.lowThreshold > 0) { + if (signalStrength > m_WatchOption.highThreshold || signalStrength < m_WatchOption.lowThreshold) { + m_cbm->callOnSuccess(tmpValue); + m_lastValue = tmpValue; + setTimer(); + } + } else { + m_cbm->callOnSuccess(tmpValue); + m_lastValue = tmpValue; + setTimer(); + } + } + } else if (m_BaseProperty->getWatchType() == 4) { + std::string key = "status"; + JSValueRef propertyStatus = getPropertyValue(context, tmpValue, key); + JSStringRef status = JSValueToStringCopy(context, propertyStatus, exception); + propertyStatus = getPropertyValue(context, m_lastValue, key); + JSStringRef prevStatus = JSValueToStringCopy(context, propertyStatus, exception); + + key = "apn"; + JSValueRef propertyApn = getPropertyValue(context, tmpValue, key); + JSStringRef apn = JSValueToStringCopy(context, propertyApn, exception); + propertyApn = getPropertyValue(context, m_lastValue, key); + JSStringRef prevApn = JSValueToStringCopy(context, propertyApn, exception); + + key = "serviceType"; + JSValueRef propertyServiceType = getPropertyValue(context, tmpValue, key); + JSStringRef serviceType = JSValueToStringCopy(context, propertyServiceType, exception); + propertyServiceType = getPropertyValue(context, m_lastValue, key); + JSStringRef prevServiceType = JSValueToStringCopy(context, propertyServiceType, exception); + + key = "mcc"; + JSValueRef propertyMcc = getPropertyValue(context, tmpValue, key); + double mcc = JSValueToNumber(context, propertyMcc, exception); + propertyMcc = getPropertyValue(context, m_lastValue, key); + double prevMcc = JSValueToNumber(context, propertyMcc, exception); + + key = "mnc"; + JSValueRef propertyMnc = getPropertyValue(context, tmpValue, key); + double mnc = JSValueToNumber(context, propertyMnc, exception); + propertyMnc = getPropertyValue(context, m_lastValue, key); + double prevMnc = JSValueToNumber(context, propertyMnc, exception); + + key = "lac"; + JSValueRef propertyLac = getPropertyValue(context, tmpValue, key); + JSStringRef lac = JSValueToStringCopy(context, propertyLac, exception); + propertyLac = getPropertyValue(context, m_lastValue, key); + JSStringRef prevLac = JSValueToStringCopy(context, propertyLac, exception); + + key = "cellid"; + JSValueRef propertyCellid = getPropertyValue(context, tmpValue, key); + JSStringRef cellid = JSValueToStringCopy(context, propertyCellid, exception); + propertyCellid = getPropertyValue(context, m_lastValue, key); + JSStringRef prevCellid = JSValueToStringCopy(context, propertyCellid, exception); + + key = "isRoaming"; + JSValueRef propertyRoam = getPropertyValue(context, tmpValue, key); + bool roam = JSValueToBoolean(context, propertyRoam); + propertyRoam = getPropertyValue(context, m_lastValue, key); + bool prevRoam = JSValueToBoolean(context, propertyRoam); + + if ( !JSStringIsEqual(status, prevStatus) || !JSStringIsEqual(apn, prevApn) || mcc != prevMcc || mnc != prevMnc + || roam != prevRoam || !JSStringIsEqual(lac, prevLac) || !JSStringIsEqual(cellid, prevCellid) || + !JSStringIsEqual(serviceType, prevServiceType)) { + m_cbm->callOnSuccess(tmpValue); + m_lastValue = tmpValue; + setTimer(); + } + } + } + } else { + m_lastValue = m_BaseProperty->getValue(context); + } + } else { + LogDebug("Watch event is cancelled aleardy."); + } +} + +void EventWatchSysteminfo::setTimer() +{ + if (m_WatchOption.timeout > 0) { + if (m_initTimer) { + ecore_timer_freeze(m_initTimer); + ecore_timer_del(m_initTimer); + m_initTimer = NULL; + } + double value = m_WatchOption.timeout/(double)1000; + m_initTimer = ecore_timer_add(value, timer_cb, this); + ecore_timer_thaw(m_initTimer); + } +} + +void EventWatchSysteminfo::removeTimer() +{ + if (m_initTimer) { + ecore_timer_freeze(m_initTimer); + ecore_timer_del(m_initTimer); + } + m_initTimer = NULL; +} + +void EventWatchSysteminfo::clearWatch() +{ + m_canceled = true; + removeTimer(); + ((TizenApis::Platform::Systeminfo::Systeminfo*)m_Systeminfo)->clearWatch(m_id); +} + +void EventWatchSysteminfo::timeoutWatch() +{ + clearWatch(); +} + +} +} +} diff --git a/src/platform/API/Systeminfo/EventWatchSysteminfo.h b/src/platform/API/Systeminfo/EventWatchSysteminfo.h new file mode 100755 index 0000000..ebebb69 --- /dev/null +++ b/src/platform/API/Systeminfo/EventWatchSysteminfo.h @@ -0,0 +1,79 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_API_SYSTEMINFO_EVENT_WATCH_SYSTEMINFO_H_ +#define WRTPLUGINS_API_SYSTEMINFO_EVENT_WATCH_SYSTEMINFO_H_ + +#include +#include +#include +#include +#include +#include +#include +#include "ISysteminfo.h" + +namespace TizenApis { +namespace Api { +namespace Systeminfo { +class EventWatchSysteminfo; + +class EventWatchSysteminfo : public WrtDeviceApis::Commons::IEvent +{ + private : + static DPL::Atomic m_uniqId; + + Api::Systeminfo::BasePropertyPtr m_BaseProperty; + Api::Systeminfo::WatchOption m_WatchOption; + void* m_Systeminfo; + + Ecore_Timer *m_initTimer; + int m_id; + int m_watchType; + bool m_canceled; + JSValueRef m_lastValue; + DPL::Mutex m_mutex; + + public : + EventWatchSysteminfo(); + ~EventWatchSysteminfo(); + + void setWatchOption(const WatchOption& watchoption); + WatchOption getWatchOption(); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getCallbackManager(); + BasePropertyPtr getBasePropertyPtr(); + void setSysteminfoPtr(void* SysteminfoPtr); + void setBasePropertyPtr(const BasePropertyPtr& baseProperty); + const char * getProperty() const; + const int getWatchType() const; + void getWatchValue(); + int getId() const; + JSValueRef getPropertyValue(JSContextRef context, JSValueRef value, std::string key); + void processGetValue(); + void setTimer(); + void removeTimer(); + void clearWatch(); + void timeoutWatch(); +}; + +typedef DPL::SharedPtr EventWatchSysteminfoPtr; +} +} +} + +#endif diff --git a/src/platform/API/Systeminfo/ISysteminfo.cpp b/src/platform/API/Systeminfo/ISysteminfo.cpp new file mode 100755 index 0000000..0740271 --- /dev/null +++ b/src/platform/API/Systeminfo/ISysteminfo.cpp @@ -0,0 +1,39 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include "ISysteminfo.h" +#include "EventGetSysteminfo.h" + +namespace TizenApis { +namespace Api { +namespace Systeminfo { +using namespace WrtDeviceApis::Commons; + +ISysteminfo::ISysteminfo() : + EventRequestReceiver(ThreadEnum::NULL_THREAD), + EventRequestReceiver(ThreadEnum::NULL_THREAD) +{ +} + +ISysteminfo::~ISysteminfo() +{ +} + +} +} +} diff --git a/src/platform/API/Systeminfo/ISysteminfo.h b/src/platform/API/Systeminfo/ISysteminfo.h new file mode 100755 index 0000000..80b50a2 --- /dev/null +++ b/src/platform/API/Systeminfo/ISysteminfo.h @@ -0,0 +1,65 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_API_ISYSTEMINFO_H_ +#define WRTPLUGINS_API_ISYSTEMINFO_H_ + +#include +#include + +#include "BaseProperties.h" +#include "EventGetSysteminfo.h" +#include "EventWatchSysteminfo.h" + +namespace TizenApis { +namespace Api { +namespace Systeminfo { + +class EventGetSysteminfo; +class EventWatchSysteminfo; +typedef DPL::SharedPtr EventGetSysteminfoPtr; +typedef DPL::SharedPtr EventWatchSysteminfoPtr; + +class ISysteminfo : + public WrtDeviceApis::Commons::EventRequestReceiver, + public WrtDeviceApis::Commons::EventRequestReceiver +{ + public: + virtual ~ISysteminfo(); + + virtual bool isPropertyValid(JSContextRef context, JSValueRef property) = 0; + virtual void get(const EventGetSysteminfoPtr& event) = 0; + virtual void watch(const EventWatchSysteminfoPtr& event) = 0; + virtual BasePropertyPtr getBasePropertyPtr(JSContextRef context, JSValueRef property) = 0; + virtual void clearWatch(const int id) = 0; + virtual bool isDuplicateWatch(const char * property) = 0; + + protected: + ISysteminfo(); + + virtual void OnRequestReceived(const EventGetSysteminfoPtr& event) = 0; + virtual void OnRequestReceived(const EventWatchSysteminfoPtr& event) = 0; +}; + +typedef DPL::SharedPtr ISysteminfoPtr; + +} +} +} + +#endif diff --git a/src/platform/API/Systeminfo/SysteminfoFactory.cpp b/src/platform/API/Systeminfo/SysteminfoFactory.cpp new file mode 100755 index 0000000..30889cd --- /dev/null +++ b/src/platform/API/Systeminfo/SysteminfoFactory.cpp @@ -0,0 +1,43 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include "SysteminfoFactory.h" + +namespace TizenApis { +namespace Api { +namespace Systeminfo { + +ISysteminfoPtr SysteminfoFactory::getSysteminfos() +{ + return ISysteminfoPtr(new Platform::Systeminfo::Systeminfo()); +} + +SysteminfoFactory& SysteminfoFactory::getInstance() +{ + static SysteminfoFactory theInstance; + return theInstance; +} + +SysteminfoFactory::SysteminfoFactory() +{ +} + +} +} +} diff --git a/src/platform/API/Systeminfo/SysteminfoFactory.h b/src/platform/API/Systeminfo/SysteminfoFactory.h new file mode 100755 index 0000000..30c5d3f --- /dev/null +++ b/src/platform/API/Systeminfo/SysteminfoFactory.h @@ -0,0 +1,45 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_API_SYSTMEINFOFACTORY_H_ +#define WRTPLUGINS_API_SYSTMEINFOFACTORY_H_ + +#include +#include "ISysteminfo.h" + +namespace TizenApis { +namespace Api { +namespace Systeminfo { + +class SysteminfoFactory : DPL::Noncopyable +{ + public: + ISysteminfoPtr getSysteminfos(); + + static SysteminfoFactory& getInstance(); + + protected: + SysteminfoFactory(); +}; + +} +} +} + +#endif + diff --git a/src/platform/API/Systeminfo/SysteminfoListener.cpp b/src/platform/API/Systeminfo/SysteminfoListener.cpp new file mode 100755 index 0000000..29badfc --- /dev/null +++ b/src/platform/API/Systeminfo/SysteminfoListener.cpp @@ -0,0 +1,65 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include "SysteminfoListener.h" +#include + +using namespace std; + +namespace TizenApis { +namespace Api { +namespace Systeminfo { + +SysteminfoListener& SysteminfoListener::getInstance() +{ + static SysteminfoListener instance; + return instance; +} + +SysteminfoListener::SysteminfoListener() : + EventGetSysteminfoAnswerReceiver(WrtDeviceApis::Commons::ThreadEnum::NULL_THREAD), + EventWatchSysteminfoAnswerReceiver(WrtDeviceApis::Commons::ThreadEnum::NULL_THREAD) +{ +} + +SysteminfoListener::~SysteminfoListener() +{ +} + +void SysteminfoListener::OnAnswerReceived(const EventGetSysteminfoPtr& event) +{ + LogDebug("Enter"); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast(event->getPrivateData()); + LogDebug("thread=" << DPL::Thread::GetCurrentThread()); + + if (!event->checkCancelled()) { + JSValueRef tmpValue = event->getValue(); + if ((WrtDeviceApis::Commons::ExceptionCodes::None == event->getExceptionCode()) && (NULL != tmpValue)) { + callbackManager->callOnSuccess(tmpValue); + } + } +} + +void SysteminfoListener::OnAnswerReceived(const EventWatchSysteminfoPtr& event) +{ +} + +} +} +} diff --git a/src/platform/API/Systeminfo/SysteminfoListener.h b/src/platform/API/Systeminfo/SysteminfoListener.h new file mode 100755 index 0000000..7c0f70d --- /dev/null +++ b/src/platform/API/Systeminfo/SysteminfoListener.h @@ -0,0 +1,55 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_API_SYSTEMINFO_LISTENER_H_ +#define WRTPLUGINS_API_SYSTEMINFO_LISTENER_H_ + +#include +#include +#include "EventGetSysteminfo.h" +#include "EventWatchSysteminfo.h" + +namespace TizenApis { +namespace Api { +namespace Systeminfo { + +typedef WrtDeviceApis::Commons::EventAnswerReceiver EventGetSysteminfoAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver EventWatchSysteminfoAnswerReceiver; + +class SysteminfoListener : public EventGetSysteminfoAnswerReceiver, public EventWatchSysteminfoAnswerReceiver +{ + private: + explicit SysteminfoListener(); + + public: + static SysteminfoListener& getInstance(); + + virtual ~SysteminfoListener(); + + protected: + virtual void OnAnswerReceived(const EventGetSysteminfoPtr& event); + + virtual void OnAnswerReceived(const EventWatchSysteminfoPtr& event); +}; + +typedef DPL::SharedPtr SysteminfoListenerPtr; +} +} +} + +#endif diff --git a/src/platform/API/Systeminfo/SysteminfoPropertyInfo.h b/src/platform/API/Systeminfo/SysteminfoPropertyInfo.h new file mode 100755 index 0000000..758e944 --- /dev/null +++ b/src/platform/API/Systeminfo/SysteminfoPropertyInfo.h @@ -0,0 +1,156 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_API_POWERINFO_H_ +#define WRTPLUGINS_API_POWERINFO_H_ + +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace Systeminfo { + +struct PowerProperties +{ + double level; + bool isCharging; + + PowerProperties() : + level(0.0), + isCharging(false) + { + } +}; + +struct CpuProperties +{ + double load; + + CpuProperties() : + load(0.0) + { + } +}; + +struct StorageProperties +{ + std::string type; + unsigned long capacity; + unsigned long availableCapacity; + bool isRemoveable; + + StorageProperties(): + type("UNKNOWN"), + capacity(0), + availableCapacity(0), + isRemoveable(false) + { + } +}; + +struct DisplayProperties +{ + unsigned long resolutionWidth; + unsigned long resolutionHeight; + unsigned long dotsPerInchWidth; + unsigned long dotsPerInchHeight; + double physicalWidth; + double physicalHeight; + double brightness; + + DisplayProperties() : + resolutionWidth(0), + resolutionHeight(0), + dotsPerInchWidth(0), + dotsPerInchHeight(0), + physicalWidth(0.0), + physicalHeight(0.0), + brightness(0.0) + { + } +}; + +struct DeviceProperties +{ + std::string imei; + std::string model; + std::string version; + std::string vendor; + + DeviceProperties() : + imei(""), + model(""), + version(""), + vendor("") + { + } +}; + +struct WifiNetworkProperties +{ + std::string status; + std::string ssid; + std::string ipAddress; + double signalStrength; + + WifiNetworkProperties() : + status(""), + ssid(""), + ipAddress(""), + signalStrength(0.0) + { + } +}; + +struct CellularNetworkProperties +{ + std::string status; + std::string apn; + std::string ipAddress; + unsigned short mcc; + unsigned short mnc; + unsigned short cellid; + unsigned short lac; + std::string serviceType; + bool isRoaming; + + + CellularNetworkProperties() : + status(""), + apn(""), + ipAddress(""), + mcc(0), + mnc(0), + cellid(0), + lac(0), + serviceType(""), + isRoaming(false) + { + } +}; + +} +} +} + +#endif diff --git a/src/platform/API/Systeminfo/config.cmake b/src/platform/API/Systeminfo/config.cmake new file mode 100755 index 0000000..4cae34c --- /dev/null +++ b/src/platform/API/Systeminfo/config.cmake @@ -0,0 +1,9 @@ +get_current_path() + +set(SRCS_PLATFORM_API_SYSTEMINFO + ${CURRENT_PATH}/SysteminfoFactory.cpp + ${CURRENT_PATH}/EventWatchSysteminfo.cpp + ${CURRENT_PATH}/SysteminfoListener.cpp + ${CURRENT_PATH}/ISysteminfo.cpp + PARENT_SCOPE +) diff --git a/src/platform/API/TimeUtil/DurationProperties.h b/src/platform/API/TimeUtil/DurationProperties.h new file mode 100755 index 0000000..8c43e67 --- /dev/null +++ b/src/platform/API/TimeUtil/DurationProperties.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#ifndef WRTPLUGINS_API_TIMEUTIL_DURATION_PROPERTIES_H_ +#define WRTPLUGINS_API_TIMEUTIL_DURATION_PROPERTIES_H_ + +#include +#include + +using namespace std; + +namespace { + const short MSECS_UNIT= 0; + const short SECONDS_UNIT = 1; + const short MINUTES_UNIT = 2; + const short HOURS_UNIT = 3; + const short DAYS_UNIT = 4; + +} + +namespace TizenApis { +namespace Api { +namespace TimeUtil { + + +struct DurationProperties +{ + long long length; + short unit; + DurationProperties() + : length(0), + unit(MSECS_UNIT) + { + } +}; + +typedef DPL::SharedPtr DurationPropertiesPtr; + +} //TimeUtil +} // Api +} // TizenApis + +#endif //WRTPLUGINS_API_TIMEUTIL_DURATION_PROPERTIES_H_ \ No newline at end of file diff --git a/src/platform/API/TimeUtil/EventSetCurrentTZDate.h b/src/platform/API/TimeUtil/EventSetCurrentTZDate.h new file mode 100755 index 0000000..e7c5f57 --- /dev/null +++ b/src/platform/API/TimeUtil/EventSetCurrentTZDate.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#ifndef WRTPLUGINS_API_TIMEUTIL_EVENT_SET_CURRENT_TZDATE_H_ +#define WRTPLUGINS_API_TIMEUTIL_EVENT_SET_CURRENT_TZDATE_H_ + +#include +#include +#include "TZDateProperties.h" + +namespace TizenApis { +namespace Api { +namespace TimeUtil { + +class EventSetCurrentTZDate : public WrtDeviceApis::Commons::IEvent +{ + bool m_result; + TZDateProperties m_properties; +public: + + EventSetCurrentTZDate() : m_result(false) { LogDebug("entered"); } + ~EventSetCurrentTZDate() { } + void setResult(bool value) { m_result = value; } + bool getResult() const { return m_result; } + TZDateProperties getTZDateProperties() const { return m_properties;} + void setTZDateProperties(const TZDateProperties &value) {m_properties = value;} + virtual void clearOnCancel(){;} +}; + +typedef DPL::SharedPtr EventSetCurrentTZDatePtr; + +} //TimeUtil +} // Api +} // TizenApis + +#endif //WRTPLUGINS_API_TIMEUTIL_EVENT_SET_CURRENT_DATETIME_H_ \ No newline at end of file diff --git a/src/platform/API/TimeUtil/ITZDate.h b/src/platform/API/TimeUtil/ITZDate.h new file mode 100755 index 0000000..e4c949b --- /dev/null +++ b/src/platform/API/TimeUtil/ITZDate.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _ABSTRACT_LAYER_ITZDATE_H_ +#define _ABSTRACT_LAYER_ITZDATE_H_ + +#include +#include +#include +#include "DurationProperties.h" +#include "TZDateProperties.h" + +namespace TizenApis { +namespace Api { +namespace TimeUtil { + +class ITZDate { +public: + enum TZDateFields { + TZDATE_ERA, + TZDATE_YEAR, + TZDATE_MONTH, + TZDATE_WEEK_OF_YEAR, + TZDATE_WEEK_OF_MONTH, + TZDATE_DATE, + TZDATE_DAY_OF_YEAR, + TZDATE_DAY_OF_WEEK, + TZDATE_DAY_OF_WEEK_IN_MONTH, + TZDATE_AM_PM, + TZDATE_HOUR, + TZDATE_HOUR_OF_DAY, + TZDATE_MINUTE, + TZDATE_SECOND, + TZDATE_MILLISECOND, + TZDATE_ZONE_OFFSET, + TZDATE_DST_OFFSET, + + TZDATE_FIELDS_COUNT, + }; + + enum DSTTransition { + PREV_TRANSITION, + NEXT_TRANSITION + }; + + ITZDate() { + ; + } + virtual ~ITZDate() { + ; + } + + virtual bool isNull() =0; + virtual long get(const TZDateFields field) =0; + virtual std::string getTimezone() =0; + virtual TZDateProperties toTimezone(const std::string timezone) =0; + virtual void set(const TZDateFields field, const long value) = 0; + + virtual long getUTC(const TZDateFields field) = 0; + virtual void setUTC(const TZDateFields field, const long value) = 0; + + virtual long long difference(const TZDateProperties &prop) =0; + virtual TZDateProperties addDuration(const DurationProperties &duration) =0; + virtual TZDateProperties toUTC() =0; + virtual TZDateProperties toLocalTimezone() =0; + virtual double getTime() =0; + virtual std::string toDateString(bool bLocale = false) =0; + virtual std::string toTimeString(bool bLocale = false)=0; + virtual std::string toString(bool bLocale = false) =0; + + virtual std::string getTimezoneAbbreviation() =0; + virtual long secondsFromUTC() =0; + virtual bool isDST() =0; + virtual TZDateProperties getDSTTransition(DSTTransition trans) =0; +}; + +typedef DPL::SharedPtr ITZDatePtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_IDATETIME_H_ */ diff --git a/src/platform/API/TimeUtil/ITimeUtil.h b/src/platform/API/TimeUtil/ITimeUtil.h new file mode 100755 index 0000000..dddc21a --- /dev/null +++ b/src/platform/API/TimeUtil/ITimeUtil.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#ifndef _ABSTRACT_LAYER_ITIMEUTIL_H_ +#define _ABSTRACT_LAYER_ITIMEUTIL_H_ + +#include +#include + +#include +#include +#include +#include "EventSetCurrentTZDate.h" + +namespace TizenApis { +namespace Api { +namespace TimeUtil{ + +using namespace WrtDeviceApis::Commons; + +class ITimeUtil +{ + public: + + + ITimeUtil() {} + + virtual ~ITimeUtil() {} + + virtual void setCurrentTZDate(const TZDateProperties &tzdate) =0; + virtual std::string getLocalTimezone( )=0; + virtual std::string getUTCTimezone() =0; + virtual std::vector getAvailableTimezones() =0; + virtual std::string getDateFormat(const bool b_shortFormat)=0; + virtual std::string getTimeFormat() =0; +}; + +typedef DPL::SharedPtr ITimeUtilPtr; + +} +} +} + +#endif /* _ABSTRACT_LAYER_ITIMEUTIL_H_ */ diff --git a/src/platform/API/TimeUtil/TZDateProperties.h b/src/platform/API/TimeUtil/TZDateProperties.h new file mode 100755 index 0000000..32cb821 --- /dev/null +++ b/src/platform/API/TimeUtil/TZDateProperties.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#ifndef WRTPLUGINS_API_TIMEUTIL_TZDATE_PROPERTIES_H_ +#define WRTPLUGINS_API_TIMEUTIL_TZDATE_PROPERTIES_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Api { +namespace TimeUtil { + +struct TZDateProperties +{ + long year; + long month; + long day; + long hours; + long minutes; + long seconds; + long milliseconds; + std::string timezone; + TZDateProperties() + : year(0), month(0), day(0), hours(0), minutes(0), seconds(0), milliseconds(0), + timezone("") + { + } +}; + + +typedef DPL::SharedPtr TZDatePropertiesPtr; + +} //TimeUtil +} // Api +} // TizenApis + +#endif //WRTPLUGINS_API_TIMEUTIL_TZDATE_PROPERTIES_H_ \ No newline at end of file diff --git a/src/platform/API/TimeUtil/TimeUtilFactory.cpp b/src/platform/API/TimeUtil/TimeUtilFactory.cpp new file mode 100755 index 0000000..197a985 --- /dev/null +++ b/src/platform/API/TimeUtil/TimeUtilFactory.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "TimeUtilFactory.h" +#include +#include + +namespace TizenApis { +namespace Api { +namespace TimeUtil { + +ITimeUtilPtr TimeUtilFactory::createTimeUtilObject() { + return ITimeUtilPtr( new Platform::TimeUtil::TimeUtil() ); +} + +ITZDatePtr TimeUtilFactory::createTZDateObject(const bool isNotNull) { + return ITZDatePtr( new Platform::TimeUtil::TZDate(isNotNull) ); +} + +ITZDatePtr TimeUtilFactory::createTZDateObject(const TZDateProperties &properties) { + return ITZDatePtr( new Platform::TimeUtil::TZDate(properties) ); +} + +TimeUtilFactory& TimeUtilFactory::getInstance() { + static TimeUtilFactory theInstance; + return theInstance; +} + +} +} +} diff --git a/src/platform/API/TimeUtil/TimeUtilFactory.h b/src/platform/API/TimeUtil/TimeUtilFactory.h new file mode 100755 index 0000000..9929ec4 --- /dev/null +++ b/src/platform/API/TimeUtil/TimeUtilFactory.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef WRTPLUGINS_API_TIMEUTILFACTORY_H_ +#define WRTPLUGINS_API_TIMEUTILFACTORY_H_ + +#include +#include + +#include "ITimeUtil.h" +#include "ITZDate.h" + +namespace TizenApis { +namespace Api { +namespace TimeUtil { + +class TimeUtilFactory : DPL::Noncopyable +{ +private: + /** + * Private constructor to provide singleton + */ + TimeUtilFactory(){;} +public: + ITimeUtilPtr createTimeUtilObject(); + ITZDatePtr createTZDateObject(const bool isNotNull = TRUE); + ITZDatePtr createTZDateObject(const TZDateProperties &properties); + + static TimeUtilFactory& getInstance(); + +}; + +} +} +} + +#endif //WRTPLUGINS_API_TIMEUTILFACTORY_H_ + diff --git a/src/platform/API/TimeUtil/TimezoneProperties.h b/src/platform/API/TimeUtil/TimezoneProperties.h new file mode 100755 index 0000000..8c36c8a --- /dev/null +++ b/src/platform/API/TimeUtil/TimezoneProperties.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _ABSTRACT_LAYER_TIMEZONEPROPERTIES_H_ +#define _ABSTRACT_LAYER_TIMEZONEPROPERTIES_H_ + +#include +#include + +namespace TizenApis { +namespace Api { +namespace TimeUtil { + +struct TimezoneProperties +{ + std::string name; + TimezoneProperties() : + name("") + { + } +}; + +typedef DPL::SharedPtr TimezonePropertiesPtr; +} // TimeUtil +} // Api +} // TizenApis + +#endif // _ABSTRACT_LAYER_TIMEZONEPROPERTIES_H_ \ No newline at end of file diff --git a/src/platform/API/TimeUtil/config.cmake b/src/platform/API/TimeUtil/config.cmake new file mode 100755 index 0000000..d452c42 --- /dev/null +++ b/src/platform/API/TimeUtil/config.cmake @@ -0,0 +1,6 @@ +get_current_path() + +set(SRCS_PLATFORM_API_TIMEUTIL + ${CURRENT_PATH}/TimeUtilFactory.cpp + PARENT_SCOPE +) diff --git a/src/platform/API/config.cmake b/src/platform/API/config.cmake new file mode 100755 index 0000000..03c98e0 --- /dev/null +++ b/src/platform/API/config.cmake @@ -0,0 +1,37 @@ +include_config_file(Filter) +include_config_file(Calendar) +include_config_file(Contact) +include_config_file(Geocoder) +include_config_file(Bluetooth) +include_config_file(Application) +include_config_file(Messaging) +include_config_file(Call) +include_config_file(TimeUtil) +include_config_file(Systeminfo) +include_config_file(NFC) + +#include_config_file(Account) +#include_config_file(Accelerometer) +#include_config_file(Orientation) +#include_config_file(Gyroscope) +#include_config_file(Filesystem) +#include_config_file(UI) +#include_config_file(Haptics) +#include_config_file(MMPlayer) +#include_config_file(Memory) +#include_config_file(Cpu) +#include_config_file(Power) +#include_config_file(Networking) +#include_config_file(Profile) +#include_config_file(Geolocation) +#include_config_file(Display) +#include_config_file(System) +#include_config_file(Widget) +#include_config_file(Device) +#include_config_file(WrtWrapper) +#include_config_file(Radio) +#include_config_file(WidgetConfiguration) +#include_config_file(FeatureLoader) +#include_config_file(Messaging) +#include_config_file(Telephony) +#include_config_file(AppLauncher) diff --git a/src/platform/CMakeLists.txt b/src/platform/CMakeLists.txt new file mode 100644 index 0000000..9ab7b00 --- /dev/null +++ b/src/platform/CMakeLists.txt @@ -0,0 +1,3 @@ +include_config_file(API) +include_config_file(commons) +include_config_file(${PLATFORM}) diff --git a/src/platform/Tizen/Application/Application.cpp b/src/platform/Tizen/Application/Application.cpp new file mode 100755 index 0000000..b3657d7 --- /dev/null +++ b/src/platform/Tizen/Application/Application.cpp @@ -0,0 +1,442 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "Application.h" +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Application { + +using namespace Api::Application; +using namespace DPL; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace Platform; + + +namespace +{ + static bool app_manager_app_list_cb(const char *package, void *user_data) + { + char *name = NULL; + char *iconPath = NULL; + char *version = NULL; + if(user_data != NULL){ + EventListInstalledApplications* event = (EventListInstalledApplications*)user_data; + + ApplicationInformationPtr appinfo(new ApplicationInformation()); + app_manager_get_app_name(package, &name); + app_manager_get_app_icon_path(package, &iconPath); + app_manager_get_app_version(package, &version); + appinfo->setName(name); + appinfo->setPackage(package); + appinfo->setIconPath(iconPath); + appinfo->setVersion(version); + + event->addApplicationInformation(appinfo); + free(name); + free(iconPath); + free(version); + } + return true; + } + + static void app_manager_app_list_changed_cb(app_manger_event_type_e event_type,const char *package, void *user_data) + { + if(user_data != NULL){ + ((Application*)user_data)->InstalledApplicationChanged(event_type, package); + } + } + + static void service_result_cb(service_h request, service_h reply, service_result_e result, void *user_data) + { + if(user_data != NULL){ + ((Application*)user_data)->launchServiceManualAnswer(request, reply, result); + } + } + + static bool service_extra_data_cb(service_h service, const char *key, void* user_data) + { + EventLaunchService* event = (EventLaunchService*)user_data; + char *value=NULL; + LogDebug(">>>service_extra_data_cb, key = "<::PostRequest(event); +} + +void Application::getApplicationInformation(const EventGetApplicationPtr& event) +{ + if (m_initialized == false) { + initialize(); + } + + EventRequestReceiver::PostRequest(event); +} + + +long Application::addApplicationListChangeListener(const EventInstalledApplicationChangedEmitterPtr& emitter) +{ + if(m_installedApplicationsEmitterPtr != NULL) + { + LogWarning("listener is already added"); + return 0; + } + m_installedApplicationsEmitterPtr = emitter; + + int result = app_manager_set_app_list_changed_cb(app_manager_app_list_changed_cb, this ); + if ( result == APP_MANAGER_ERROR_NONE) + { + LogWarning("application list listener is set successfully."); + } + else if( result == APP_MANAGER_ERROR_INVALID_PARAMETER ) + { + LogWarning("app_manager_set_app_list_changed_cb() returns APP_MANAGER_ERROR_INVALID_PARAMETER"); + EventInstalledApplicationChangedPtr event(new EventInstalledApplicationChanged()); + event->setExceptionCode(ExceptionCodes::InvalidArgumentException); + m_installedApplicationsEmitterPtr->emit(event); + } + return m_installedApplicationsEmitterPtr->getId(); + +} + +void Application::removeApplicationListChangeListener(const EventInstalledApplicationChangedEmitter::IdType id) +{ + if(m_installedApplicationsEmitterPtr) + { + if(m_installedApplicationsEmitterPtr->getId() == id) + { + LogWarning("id matched"); + m_installedApplicationsEmitterPtr = EventInstalledApplicationChangedEmitterPtr(NULL); + app_manager_unset_app_list_changed_cb(); + } + else + LogInfo("id does not match with listener"); + } +} + +void Application::launchService(const EventLaunchServicePtr& event) +{ + LogDebug("<<<"); + + if (m_initialized == false) { + initialize(); + } + + EventRequestReceiver::PostRequest(event); + + LogDebug(">>>"); +} + +void Application::InstalledApplicationChanged(app_manger_event_type_e event_type,const char *package) +{ + char *name = NULL; + char *iconPath = NULL; + char *version = NULL; + + EventInstalledApplicationChangedPtr event(new EventInstalledApplicationChanged()); + ApplicationInformationPtr appinfo(new ApplicationInformation()); + + appinfo->setPackage(package); + if(event_type != APP_MANAGER_EVENT_UNINSTALLED) + { + app_manager_get_app_name(package, &name); + app_manager_get_app_icon_path(package, &iconPath); + app_manager_get_app_version(package, &version); + + appinfo->setName(name); + appinfo->setIconPath(iconPath); + appinfo->setVersion(version); + } + + if(event_type == APP_MANAGER_EVENT_INSTALLED) + { + event->setEventCode(APPLICATON_EVENT_CODE_INSTALLED); + LogDebug("event : APP_MANAGER_EVENT_INSTALLED, package name : "<setEventCode(APPLICATON_EVENT_CODE_UNINSTALLED); + LogDebug("event : APP_MANAGER_EVENT_UNINSTALLED, package name : "<setEventCode(APPLICATON_EVENT_CODE_UPDATED); + LogDebug("event : APP_MANAGER_EVENT_UPDATED, package name : "<setApplicationInformation(appinfo); + m_installedApplicationsEmitterPtr->emit(event); + + if(name != NULL ) + free(name); + if(iconPath != NULL ) + free(iconPath); + if(version != NULL ) + free(version); + + LogDebug("<<>>launchServiceManualAnswer"); + + //EventLaunchServicePtr event(new EventLaunchService()); + + if(result == SERVICE_RESULT_SUCCEEDED) + { + // onsuccess + LogDebug("SERVICE_RESULT_SUCCEEDED in service_result_cb"); + + //after service_foreach_extra_data() called, extra_data must be set to event + int result = service_foreach_extra_data(reply, service_extra_data_cb, m_eventLaunchServicePtr.Get()); + if( result == SERVICE_ERROR_NONE) + { + LogDebug("service_foreach_extra_data() success"); + } + else + { + LogDebug("service_foreach_extra_data() failed"); + } + + // FIXME : if reply service is failed, then we need call replyError callback + m_eventLaunchServicePtr->setCallbackType(EventLaunchService::APPLICATION_SERVICE_REPLY_SUCCESS_CALLBACK); + + } + else if(result == SERVICE_RESULT_FAILED) + { + // onfail + LogDebug("SERVICE_RESULT_FAILED in service_result_cb"); + //after service_foreach_extra_data() called, extra_data must be set to event + int result = service_foreach_extra_data(reply, service_extra_data_cb, m_eventLaunchServicePtr.Get()); + if( result == SERVICE_ERROR_NONE) + { + LogDebug("service_foreach_extra_data() success"); + } + else + { + LogDebug("service_foreach_extra_data() failed"); + } + + m_eventLaunchServicePtr->setCallbackType(EventLaunchService::APPLICATION_SERVICE_REPLY_FAIL_CALLBACK); + } + else if(result == SERVICE_RESULT_CANCELED) + { + // oncancel + m_eventLaunchServicePtr->setCallbackType(EventLaunchService::APPLICATION_SERVICE_REPLY_CANCEL_CALLBACK); + LogDebug("SERVICE_RESULT_CANCELED in service_result_cb"); + } + + // FIXME : if there is no callback , then we don't need to call ManualAnswer. + + WrtDeviceApis::Commons::EventRequestReceiver::ManualAnswer(m_eventLaunchServicePtr); + service_destroy(request); + +// EventRequestReceiver::ManualAnswer(event); + LogDebug("<<getEventType() == EventListInstalledApplications::APPMANAGER_LIST_INSTALLED_APPLICATIONS) { + int result = app_manager_foreach_app_installed(app_manager_app_list_cb, event.Get()); + if( result != 0) + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + + } else if(event->getEventType() == EventListInstalledApplications::APPMANAGER_LIST_RUNNING_APPLICATIONS) { + int result = app_manager_foreach_app_running(app_manager_app_list_cb, event.Get()); + if( result != 0) + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } else { + LogError("[ERROR] UNKNOWN EVENT TYPE"); + event->setExceptionCode(Commons::ExceptionCodes::UnknownException); + } +} + +void Application::OnRequestReceived(const Api::Application::EventGetApplicationPtr& event) +{ + char *name = NULL; + char *iconPath = NULL; + char *version = NULL; + std::string strPackage = event->getPackage(); + + ApplicationInformationPtr appinfo(new ApplicationInformation()); + LogInfo("package name to get information : "<setExceptionCode(Commons::ExceptionCodes::NotFoundException); + } + else + { + if( app_manager_get_app_version(strPackage.c_str(), &version) <0) + { + LogWarning("can not get the version information of "<setName(name); + appinfo->setPackage(strPackage.c_str()); + appinfo->setIconPath(iconPath); + appinfo->setVersion(version); + event->setApplicationInformation(appinfo); + } + + if(name) + free(name); + if(iconPath) + free(iconPath); + if(version) + free(version); +} + +void Application::OnRequestReceived(const Api::Application::EventLaunchServicePtr& event) +{ + LogDebug("<<<"); + m_eventLaunchServicePtr = event; + ApplicationServiceRequestPtr appservice= event->getServiceRequest(); + + // from now on we will have to call answer manually + event->switchToManualAnswer(); + + service_h service; + service_create(&service); + service_set_operation(service, appservice->getOperation().c_str() ); + + if( appservice->getPackage().compare("") != 0) + { + LogDebug("package name is "<getPackage()); + service_set_package(service, appservice->getPackage().c_str() ); + } + + if( appservice->getUri().compare("") != 0) + { + LogDebug("appservice.uri is not null"); + service_set_uri(service, appservice->getUri().c_str() ); + } + + if( appservice->getMime().compare("") != 0) + { + LogDebug("mime is "<getMime()); + service_set_mime(service, appservice->getMime().c_str() ); + } + + ApplicationServiceExtraDataArrayPtr extraDataArray= appservice->getExtraDataArray(); + if(extraDataArray) + { + for (size_t i = 0; i < extraDataArray->size(); ++i) { + LogDebug("extraData.key= " <at(i)->getKey()<<"extraData.value = "<at(i)->getValue()); + + service_add_extra_data(service, extraDataArray->at(i)->getKey().c_str(), extraDataArray->at(i)->getValue().c_str()); + } + } + + int result = service_send_launch_request (service, service_result_cb , this); + + switch (result){ + case SERVICE_ERROR_NONE : + LogDebug("service_send_launch_request successful"); + m_eventLaunchServicePtr->setCallbackType(EventLaunchService::APPLICATION_SERVICE_CALLBACK); + break; + case SERVICE_ERROR_INVALID_PARAMETER: + LogDebug("service_send_launch_request returns SERVICE_ERROR_INVALID_PARAMETER"); + m_eventLaunchServicePtr->setExceptionCode(Commons::ExceptionCodes::InvalidArgumentException); + break; + case SERVICE_ERROR_OUT_OF_MEMORY: + LogDebug("service_send_launch_request returns SERVICE_ERROR_OUT_OF_MEMORY"); + m_eventLaunchServicePtr->setExceptionCode(Commons::ExceptionCodes::PlatformException); + break; + case SERVICE_ERROR_APP_NOT_FOUND: + LogDebug("service_send_launch_request returns SERVICE_ERROR_APP_NOT_FOUND"); + m_eventLaunchServicePtr->setExceptionCode(Commons::ExceptionCodes::NotFoundException); + break; + default: + LogDebug("service_send_launch_request returns UNKNOWN ERROR!!!"); + m_eventLaunchServicePtr->setExceptionCode(Commons::ExceptionCodes::UnknownException); + break; + } + EventRequestReceiver::ManualAnswer(m_eventLaunchServicePtr); + LogDebug(">>>"); +} + +void Application::initialize() +{ + if (!m_initialized) { + DPL::Mutex::ScopedLock lock(&m_initializationMutex); + if (!m_initialized) { + + } + } +} + +} +} +} diff --git a/src/platform/Tizen/Application/Application.h b/src/platform/Tizen/Application/Application.h new file mode 100755 index 0000000..17b6c77 --- /dev/null +++ b/src/platform/Tizen/Application/Application.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_PLATFORM_APPLICATION_H_ +#define TIZENAPIS_PLATFORM_APPLICATION_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +using namespace TizenApis::Api::Application; + +namespace TizenApis { +namespace Platform { +namespace Application { + +class Application: public IApplication { + friend class ApplicationFactory; + +public: + Application(); + virtual ~Application(); + virtual void listApplications(const EventListInstalledApplicationsPtr& event); + virtual void getApplicationInformation(const EventGetApplicationPtr& event); + virtual long addApplicationListChangeListener(const EventInstalledApplicationChangedEmitterPtr& emitter); + virtual void removeApplicationListChangeListener(const EventInstalledApplicationChangedEmitter::IdType id); + virtual void launchService(const EventLaunchServicePtr& event); + void launchServiceManualAnswer(service_h request, service_h reply, service_result_e result); + void InstalledApplicationChanged(app_manger_event_type_e event_type,const char *package); + +protected: + virtual void OnRequestReceived(const EventListInstalledApplicationsPtr& event); + virtual void OnRequestReceived(const EventGetApplicationPtr& event); + virtual void OnRequestReceived(const EventLaunchServicePtr& event); + +private: + void initialize(); + + DPL::Mutex m_initializationMutex; + bool m_initialized; + Api::Application::EventLaunchServicePtr m_eventLaunchServicePtr; + EventInstalledApplicationChangedEmitterPtr m_installedApplicationsEmitterPtr; +}; + +} +} +} + +#endif diff --git a/src/platform/Tizen/Application/config.cmake b/src/platform/Tizen/Application/config.cmake new file mode 100755 index 0000000..a00a3e5 --- /dev/null +++ b/src/platform/Tizen/Application/config.cmake @@ -0,0 +1,27 @@ +get_current_path() + +pkg_search_module(capi-appfw-app-manager REQUIRED capi-appfw-app-manager) +pkg_search_module(capi-appfw-application REQUIRED capi-appfw-application) +pkg_search_module(wrt-deviceapis-commons REQUIRED wrt-deviceapis-commons) +pkg_search_module(wrt-deviceapis-commons-javascript REQUIRED wrt-deviceapis-commons-javascript) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_APPLICATION + ${capi-appfw-app-manager_INCLUDE_DIRS} + ${capi-appfw-application_INCLUDE_DIRS} + ${wrt-deviceapis-commons_INCLUDE_DIRS} + ${wrt-deviceapis-commons-javascript_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_APPLICATION + ${capi-appfw-app-manager_LIBRARIES} + ${capi-appfw-application_LIBRARIES} + ${wrt-deviceapis-commons_LIBRARIES} + ${wrt-deviceapis-commons-javascript_LIBRARIES} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_APPLICATION + ${CURRENT_PATH}/Application.cpp + PARENT_SCOPE +) diff --git a/src/platform/Tizen/Bluetooth/BluetoothAdapterManager.cpp b/src/platform/Tizen/Bluetooth/BluetoothAdapterManager.cpp new file mode 100755 index 0000000..ace36b3 --- /dev/null +++ b/src/platform/Tizen/Bluetooth/BluetoothAdapterManager.cpp @@ -0,0 +1,1125 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "BluetoothAdapterManager.h" +#include +#include + + + +using namespace TizenApis::Api; +using namespace WrtDeviceApis; +using namespace DPL; + +namespace TizenApis { +namespace Platform { +namespace Bluetooth { + +bool BluetoothAdapterManager::m_btPowered = false; +bool BluetoothAdapterManager::m_btGetDeviceEvent = false; +int BluetoothAdapterManager::m_currentServiceSocket = -1; + + +namespace { + +static void capi_callback_bt_name_changed(char *device_name, void *user_data) +{ + ((BluetoothAdapterManager*)user_data)->setAdapterNameManualAnswer(device_name); +} + + + + +static void capi_callback_bt_state_changed(int result, bt_adapter_state_e adapter_state, void* user_data) +{ + if( result == BT_ERROR_NONE ) + { + LogDebug("State Changed" << adapter_state); + ((BluetoothAdapterManager*)user_data)->setPoweredManualAnswer(); + } + else + { + LogDebug("Error"); + } +} + +static void capi_callback_bt_discovery_state_changed(int result, + bt_adapter_device_discovery_state_e discovery_state, bt_adapter_device_discovery_info_s *discovery_info, void *user_data) +{ + LogDebug("Discovery state" << discovery_state); + if (discovery_state == BT_ADAPTER_DEVICE_DISCOVERY_FOUND && discovery_info != NULL) + { + LogDebug("found device" << discovery_info->remote_name << " " << discovery_info->remote_address); + } + + LogDebug("Discovery state" << discovery_state); + ((BluetoothAdapterManager*)user_data)->discoveryDevicesCallbackEmit(result, discovery_state, discovery_info); + +} + + +static bool capi_callback_bt_adapter_bonded_device(bt_device_info_s *device_info, void *user_data) +{ + if( device_info != NULL ) + { + LogDebug("address " << device_info->remote_address << " " << device_info->remote_name); + ((BluetoothAdapterManager*)user_data)->getKnownDevicesManualAnswer (device_info); + } + + return true; +} + +static bool capi_callback_bt_adapter_bonded_device_find(bt_device_info_s *device_info, void *user_data) +{ + bool ret = true; + if( device_info != NULL ) + { + LogDebug("address " << device_info->remote_address << " " << device_info->remote_name); + ret = ((BluetoothAdapterManager*)user_data)->getDeviceManualAnswer (device_info); + } + + return ret;; +} + + +static void capi_callback_bt_device_bond_created(int result, bt_device_info_s *device_info, void *user_data) +{ + ((BluetoothAdapterManager*)user_data)->createBondingManualAnswer(result, device_info); +} + +static void capi_callback_bt_device_bond_destroyed(int result, char* remote_address, void *user_data) +{ + ((BluetoothAdapterManager*)user_data)->destroyBondingManualAnswer(result); +} + +static void capi_callback_bt_socket_connection_state_changed(int result, bt_socket_connection_state_e connection_state, + bt_socket_connection_s *connection, void *user_data) +{ + LogDebug("OK"); + + ((BluetoothAdapterManager*)user_data)->registerRFCOMMServiceByUUIDCallbackEmit(result, connection_state, connection); +} +} + +BluetoothAdapterManager::BluetoothAdapterManager() +{ + LogDebug("Enter"); + Init(); + m_btPowered = canUseBluetooth(); +} + +BluetoothAdapterManager::~BluetoothAdapterManager() +{ + LogDebug("Enter"); +} + +void BluetoothAdapterManager::Init() +{ + LogDebug("Enter"); + + bt_initialize(); +} + +bool BluetoothAdapterManager::canUseBluetooth() +{ + bt_adapter_state_e state; + int ret; + + ret = bt_adapter_get_state(&state); + + if (ret == BT_ERROR_NONE && state == BT_ADAPTER_ENABLED) + { + return true; + } + else + { + return false; + } +} + + +std::string BluetoothAdapterManager::getName() +{ + char* name = NULL; + std::string str = ""; + + if (bt_adapter_get_name(&name) == BT_ERROR_NONE) + { + LogDebug("OK"); + + if (name != NULL) + { + LogDebug("Set"); + str = name; + free(name); + } + } + return str; +} + +std::string BluetoothAdapterManager::getAddress() +{ + char* address = NULL; + std::string str = ""; + + if (bt_adapter_get_address(&address) == BT_ERROR_NONE) + { + LogDebug("OK"); + if (address != NULL) + { + LogDebug("Set"); + str = address; + free(address); + } + } + return str; + +} + +bool BluetoothAdapterManager::getPowered() +{ + bt_adapter_state_e state; + + if (bt_adapter_get_state(&state) == BT_ERROR_NONE) + { + if (state == BT_ADAPTER_ENABLED) + { + return true; + } + } + + return false; +} + +bool BluetoothAdapterManager::getVisibility() +{ + bt_adapter_visibility_mode_e mode; + + if (bt_adapter_get_visibility(&mode) == BT_ERROR_NONE) + { + if (mode != BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE) + { + return true; + } + } + return false; +} + +void BluetoothAdapterManager::setPowered(const EventBTSetPoweredPtr& event) +{ + LogDebug("Enter"); + + if (event->isEnableRequested()) + { + Init(); + } + + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::setPoweredManualAnswer() +{ + LogDebug("Enter"); + + m_btPowered = canUseBluetooth(); + bt_adapter_unset_state_changed_cb(); + + if (m_EventBTSetPoweredPtr->isEnableRequested()) + { + if (m_btPowered == true) + { + m_EventBTSetPoweredPtr->setExceptionCode(Commons::ExceptionCodes::None); + } + else + { + m_EventBTSetPoweredPtr->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + } + else + { + if (m_btPowered == false) + { + m_EventBTSetPoweredPtr->setExceptionCode(Commons::ExceptionCodes::None); + } + else + { + m_EventBTSetPoweredPtr->setExceptionCode(Commons::ExceptionCodes::PlatformException); + + } + } + EventRequestReceiver::ManualAnswer(m_EventBTSetPoweredPtr); +} + +void BluetoothAdapterManager::setVisible(const EventBTSetVisiblePtr& event) +{ + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::discoveryDevicesEmitter(const EventBTOnDiscoveryDevicesEmitterPtr& emitter) + +{ + LogDebug("Enter"); + + int ret = 0; + + m_discoverDevicesEmitter = emitter; + + try + { + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + if ((ret = bt_adapter_set_device_discovery_state_changed_cb(capi_callback_bt_discovery_state_changed, + (void*)this))!= BT_ERROR_NONE) + { + ThrowMsg(Commons::UnknownException, "platform exception error" << ret); + } + + if ((ret = bt_adapter_start_device_discovery() != BT_ERROR_NONE)) + { + ThrowMsg(Commons::UnknownException, "device discovery fail" << ret); + } + LogDebug("OK Discovery Start"); + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + bt_adapter_unset_device_discovery_state_changed_cb(); + + EventBTOnDiscoveryDevicesPtr event(new EventBTOnDiscoveryDevices()); + event->setExceptionCode(ex.getCode()); + m_discoverDevicesEmitter->emit(event); + } +} + + +void BluetoothAdapterManager::discoveryDevicesCallbackEmit(unsigned short error, unsigned short state, + bt_adapter_device_discovery_info_s *discovery_info) + +{ + BluetoothDeviceData device; + EventBTOnDiscoveryDevicesPtr event(new EventBTOnDiscoveryDevices()); + unsigned int index = 0; + + try + { + if (discovery_info != NULL) + { + device.address = discovery_info->remote_address; + device.name = discovery_info->remote_name; + device.btClass.major = discovery_info->bt_class.major_device_class; + device.btClass.minor = discovery_info->bt_class.minor_device_class; + device.btClass.majorServiceMask = discovery_info->bt_class.major_service_class_mask; + } + + switch(state) + { + case BT_ADAPTER_DEVICE_DISCOVERY_STARTED: + event->setDiscoveryState(EventBTOnDiscoveryDevices::STARTED); + break; + case BT_ADAPTER_DEVICE_DISCOVERY_FOUND: + event->setDiscoveryState(EventBTOnDiscoveryDevices::DISCOVERYING); + event->addDevice(device); + m_Devices.push_back(device); + break; + case BT_ADAPTER_DEVICE_DISCOVERY_FINISHED: + event->setDiscoveryState(EventBTOnDiscoveryDevices::FINISHED); + + for (index = 0; index < m_Devices.size(); index++) + { + event->addDevice(m_Devices[index]); + } + bt_adapter_unset_device_discovery_state_changed_cb(); + break; + default: + ThrowMsg(Commons::UnknownException, "device discovery fail"); + } + event->setExceptionCode(Commons::ExceptionCodes::None); + m_discoverDevicesEmitter->emit(event); + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + bt_adapter_unset_device_discovery_state_changed_cb(); + m_discoverDevicesEmitter->emit(event); + } +} + +void BluetoothAdapterManager::getKownDevices(const EventBTGetKnownDevicesPtr& event) +{ + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::updateDevice(BluetoothDeviceData &device) +{ + unsigned int i = 0; + LogDebug("Enter"); + + for (i = 0; i < m_Devices.size(); i++) + { + if (device.address == m_Devices[i].address && + device.name == m_Devices[i].name) + { + m_Devices[i].isBonded = device.isBonded; + m_Devices[i].isConnected = device.isConnected; + m_Devices[i].isTrusted = device.isTrusted; + m_Devices[i].btClass = device.btClass; + m_Devices[i].uuids = device.uuids; + + } + } + + if (i == m_Devices.size()) + { + m_Devices.push_back(device); + } +} + +int BluetoothAdapterManager::findDevice(std::string address, BluetoothDeviceData& device) +{ + unsigned int i = 0; + + for (i = 0; i < m_Devices.size(); i++) + { + if (address == m_Devices[i].address) + { + device = m_Devices[i]; + return BT_ERROR_NONE; + } + } + return BT_ERROR_OPERATION_FAILED; +} + +void BluetoothAdapterManager::getKnownDevicesManualAnswer(bt_device_info_s *device_info) +{ + LogDebug("Enter"); + + BluetoothDeviceData device; + int index = 0; + + if (device_info != NULL) + { + + device.address = device_info->remote_address; + device.name = device_info->remote_name; + + device.btClass.major = device_info->bt_class.major_device_class; + device.btClass.minor = device_info->bt_class.minor_device_class; + device.btClass.majorServiceMask = device_info->bt_class.major_service_class_mask; + + device.isBonded = device_info->is_bonded; + device.isConnected = device_info->is_connected; + device.isTrusted = device_info->is_authorized; + + if (device_info->service_uuid != NULL) + { + for (index = 0; index < device_info->service_count; index++) + { + if (device_info->service_uuid[index] != NULL) + { + device.uuids.push_back(device_info->service_uuid[index]); + } + } + } + else + { + LogDebug("uuid is null"); + } + updateDevice(device); + m_EventBTGetKnownDevicesPtr->addDevice(device); + } + +} + +void BluetoothAdapterManager::getDevice(const EventBTGetDevicePtr& event) +{ + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + + +bool BluetoothAdapterManager::getDeviceManualAnswer(bt_device_info_s *device_info) +{ + std::string address = ""; + + if (device_info != NULL) + { + address = device_info->remote_address; + } + + BluetoothDeviceData device; + int index = 0; + + device.address = device_info->remote_address; + device.name = device_info->remote_name; + + device.btClass.major = device_info->bt_class.major_device_class; + device.btClass.minor = device_info->bt_class.minor_device_class; + device.btClass.majorServiceMask = device_info->bt_class.major_service_class_mask; + + + device.isBonded = device_info->is_bonded; + device.isConnected = device_info->is_connected; + device.isTrusted = device_info->is_authorized; + + LogDebug("Enter Found " << device.address << " " << device.name << " " << device.btClass.major << " " << device.btClass.minor); + + if (device_info->service_uuid != NULL) + { + + for (index = 0; index < device_info->service_count; index++) + { + if (device_info->service_uuid[index] != NULL) + { + device.uuids.push_back(device_info->service_uuid[index]); + } + } + } + else + { + LogDebug("service uuid null"); + } + + if (m_btGetDeviceEvent) + { + LogDebug("Enter - getDeviceManualAnswer" << address << ":" << m_EventBTGetDevicePtr->getAddress()); + + if (address == m_EventBTGetDevicePtr->getAddress()) + { + updateDevice(device); + m_EventBTGetDevicePtr->setDevice(device); + return false; + } + } + else + { + updateDevice(device); + } + + return true; +} + + + +void BluetoothAdapterManager::createBonding(const EventBTCreateDestroyBondingPtr& event) +{ + LogDebug("Post Event EventBTCreateDestroyBonding"); + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::createBondingManualAnswer(unsigned short error, bt_device_info_s *device_info) +{ + int index = 0; + + if (error == BT_ERROR_NONE) + { + LogDebug("createBondingManualAnswer"); + + BluetoothDeviceData device; + device.address = device_info->remote_address; + device.name = device_info->remote_name; + device.isBonded = device_info->is_bonded; + device.isConnected = device_info->is_connected; + device.isTrusted = device_info->is_authorized; + + if (device_info->service_uuid != NULL) + { + for (index = 0; index < device_info->service_count; index++) + { + if (device_info->service_uuid[index] != NULL) + { + device.uuids.push_back(device_info->service_uuid[index]); + } + } + } + else + { + LogDebug("service uuid null"); + } + m_EventBTCreateDestroyBondingPtr->setExceptionCode(Commons::ExceptionCodes::None); + m_EventBTCreateDestroyBondingPtr->setDevice(device); + } + else + { + m_EventBTCreateDestroyBondingPtr->setExceptionCode(Commons::ExceptionCodes::UnknownException); + } + bt_device_unset_bond_created_cb(); + EventRequestReceiver::ManualAnswer(m_EventBTCreateDestroyBondingPtr); +} + + + +void BluetoothAdapterManager::destroyBonding(const EventBTCreateDestroyBondingPtr& event) +{ + LogDebug("Post Event EventBTCreateDestroyBonding"); + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::destroyBondingManualAnswer(unsigned short error) +{ + if (error == BT_ERROR_NONE) + { + m_EventBTCreateDestroyBondingPtr->setExceptionCode(Commons::ExceptionCodes::None); + } + else + { + m_EventBTCreateDestroyBondingPtr->setExceptionCode(Commons::ExceptionCodes::UnknownException); + } + bt_device_unset_bond_destroyed_cb(); + EventRequestReceiver::ManualAnswer(m_EventBTCreateDestroyBondingPtr); +} + + +void BluetoothAdapterManager::registerRFCOMMServiceByUUIDCallbackEmit(unsigned short error, + bt_socket_connection_state_e connectionState, bt_socket_connection_s *connection) +{ + LogDebug("OK"); + + EventBTRegisterRFCOMMPtr event(new EventBTRegisterRFCOMM()); + bt_socket_unset_connection_state_changed_cb() ; + int ret = 0; + + if (error == BT_ERROR_NONE) + { + if (connectionState == BT_SOCKET_CONNECTED) + { + BluetoothDeviceData deviceData; + BluetoothSocketData socketData; + std::map::iterator it; + + event->setConnectionState(EventBTRegisterRFCOMM::REGISTER_CONNECTED); + + m_btGetDeviceEvent = false; + + if ((ret = bt_adapter_foreach_bonded_device(capi_callback_bt_adapter_bonded_device_find, (void*)this)) == BT_ERROR_NONE) + { + findDevice(connection->remote_address, deviceData); + } + + deviceData.isConnected = true; + + if (connection->local_role == BT_SOCKET_SERVER) + { + socketData.isServer = true; + } + else + { + socketData.isServer = false; + } + + socketData.protocol = PROTOCOL_TYPE_RFCOMM_VALUE_INT; + + socketData.connectedSocket = connection->socket_fd; + socketData.registeredSocket = m_currentServiceSocket; + socketData.state = SOCKET_STATE_OPEN_VALUE_INT; + socketData.uuid = m_uuid; + socketData.peerDevice = deviceData; + + if (m_socketMap.find(deviceData.address) != m_socketMap.end()) + { + LogDebug("Found same device, remove!"); + m_socketMap.erase(it); + } + + m_socketMap[deviceData.address] = socketData; + event->setSocketData(socketData); + event->setExceptionCode(Commons::ExceptionCodes::None); + } + else + { + event->setConnectionState(EventBTRegisterRFCOMM::REGISTER_DISCONNECTED); + } + } + else + { + event->setExceptionCode(Commons::ExceptionCodes::UnknownException); + } + m_registerRFCOMMEmitter->emit(event); + + +} +long BluetoothAdapterManager::registerRFCOMMServiceByUUID(const EventBTRegisterRFCOMMEmitterPtr& emitter, + std::string uuid, std::string name, unsigned short int security) +{ + LogDebug("EventBTRegisterRFCOMMPtr"); + + int ret = 0; + m_registerRFCOMMEmitter = emitter; + m_uuid = uuid; + m_name = name; + + try + { + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + if (getVisibility() == false) + { + ThrowMsg(Commons::UnknownException, "please set visivility"); + } + + if((ret = bt_socket_create_rfcomm(uuid.data(), &m_currentServiceSocket)) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "service socket creation error" << ret); + } + + if( bt_socket_set_connection_state_changed_cb(capi_callback_bt_socket_connection_state_changed, this) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "unkown platfrom exception"); + } + + if( bt_socket_listen_and_accept_rfcomm(m_currentServiceSocket, 1) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "service socket register error"); + } + EventBTRegisterRFCOMMPtr event(new EventBTRegisterRFCOMM()); + event->setConnectionState(EventBTRegisterRFCOMM::REGISTER_SUCCESS); + event->setExceptionCode(Commons::ExceptionCodes::None); + m_registerRFCOMMEmitter->emit(event); + + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + EventBTRegisterRFCOMMPtr event(new EventBTRegisterRFCOMM()); + event->setExceptionCode(ex.getCode()); + m_registerRFCOMMEmitter->emit(event); + } + return m_currentServiceSocket; +} + +void BluetoothAdapterManager::unregisterRFCOMMService(const EventBTUnregisterRFCOMMServicePtr& event) +{ + LogDebug("EventBTUnregisterRFCOMMServicePtr"); + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::setAdapterName(const EventBTSetNamePtr& event) +{ + LogDebug("EventBTSetNamePtr"); + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::setAdapterNameManualAnswer(char* deviceName) +{ + LogDebug("Enter"); + + if (deviceName != NULL) + { + if (strcmp(deviceName, m_EventBTSetNamePtr->getName().c_str()) != 0) + { + m_EventBTSetNamePtr->setExceptionCode(Commons::ExceptionCodes::UnknownException); + } + else + { + m_EventBTSetNamePtr->setExceptionCode(Commons::ExceptionCodes::None); + } + } + else + { + m_EventBTSetNamePtr->setExceptionCode(Commons::ExceptionCodes::UnknownException); + } + + EventRequestReceiver::ManualAnswer(m_EventBTSetNamePtr); +} + + + +void BluetoothAdapterManager::stopDiscovery(const EventBTStopDiscoveryPtr& event) +{ + LogDebug("EventBTStopDiscoveryPtr"); + EventRequestReceiver::PostRequest(event); + +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTSetPoweredPtr& event) +{ + int ret = 0; + + try + { + event->switchToManualAnswer(); + m_EventBTSetPoweredPtr = event; + + if( bt_adapter_set_state_changed_cb(capi_callback_bt_state_changed, (void*)this) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + + if (event->isEnableRequested()) + { + ret = bt_adapter_enable(); + + switch(ret) + { + case BT_ERROR_NONE: + return; + case BT_ERROR_ALREADY_DONE: + event->setExceptionCode(Commons::ExceptionCodes::None); + m_btPowered = canUseBluetooth(); + bt_adapter_unset_state_changed_cb(); + EventRequestReceiver::ManualAnswer(event); + break; + case BT_ERROR_NOT_INITIALIZED: + ThrowMsg(Commons::UnknownException, "bt is not initialized"); + break; + case BT_ERROR_RESOURCE_BUSY: + default: + ThrowMsg(Commons::SecurityException, "bt is busy"); + break; + } + } + else + { + LogDebug("Disable"); + ret = bt_adapter_disable(); + + if (ret == BT_ERROR_NONE) + { + return; + } + ThrowMsg(Commons::UnknownException, "can not disable bt"); + } + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + bt_adapter_unset_state_changed_cb(); + EventRequestReceiver::ManualAnswer(event); + } +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTSetVisiblePtr& event) +{ + LogDebug("Enter"); + int ret = 0; + bt_adapter_visibility_mode_e visibility_mode = BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE; + bt_adapter_visibility_mode_e current_visibility = BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE; + + try + { + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + if (event->isVisibleRequested()) + { + if (event->getTimeout() == 0) + { + visibility_mode = BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE; + } + else + { + visibility_mode = BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE; + } + } + else + { + visibility_mode = BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE; + + } + + if (bt_adapter_get_visibility(¤t_visibility) != BT_ERROR_NONE) + { + ThrowMsg(Commons::UnknownException, "get visibility error" << ret); + } + + + if (current_visibility == visibility_mode) + { + LogDebug("already same visiblity"); + event->setExceptionCode(Commons::ExceptionCodes::None); + return; + } + + LogDebug("bt_adapter_set_visibility " << visibility_mode << " " << event->getTimeout()); + + if ((ret = bt_adapter_set_visibility(visibility_mode, event->getTimeout()) != BT_ERROR_NONE)) + { + ThrowMsg(Commons::UnknownException, "set visibility error" << ret); + } + event->setExceptionCode(Commons::ExceptionCodes::None); + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } +} + + +void BluetoothAdapterManager::OnRequestReceived(const EventBTGetKnownDevicesPtr& event) +{ + LogDebug("EventBTGetKnownDevicesPtr Enter"); + + int ret = 0; + + try + { + m_EventBTGetKnownDevicesPtr = event; + + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + if ((ret = bt_adapter_foreach_bonded_device(capi_callback_bt_adapter_bonded_device, (void*)this))!= BT_ERROR_NONE) + { + ThrowMsg(Commons::UnknownException, "bt_adapter_foreach_bonded_device" << ret); + } + + LogDebug("Get Konwn device"); + + event->setExceptionCode(Commons::ExceptionCodes::None); + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTGetDevicePtr& event) +{ + LogDebug("EventBTGetDevicePtr Enter"); + + int ret = 0; + + try + { + m_EventBTGetDevicePtr = event; + + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + m_btGetDeviceEvent = true; + + if ((ret = bt_adapter_foreach_bonded_device(capi_callback_bt_adapter_bonded_device_find, (void*)this))!= BT_ERROR_NONE) + { + ThrowMsg(Commons::UnknownException, "bt_adapter_foreach_bonded_device" << ret); + } + m_btGetDeviceEvent = false; + + LogDebug("EventBTGetDevicePtr"); + event->setExceptionCode(Commons::ExceptionCodes::None); + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTCreateDestroyBondingPtr& event) +{ + LogDebug("Enter"); + + int ret = 0; + const char *device_addr = (event->getAddress()).data(); + + try + { + m_EventBTCreateDestroyBondingPtr = event; + event->switchToManualAnswer(); + + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + + if ((event->getAddress()).length() == 0) + { + ThrowMsg(Commons::PlatformException, "address error" << ret); + } + + + if (event->isCreateBonding()) + { + + if ((ret = bt_device_set_bond_created_cb(capi_callback_bt_device_bond_created, (void*)this)) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::PlatformException, "bt_device_set_bond_created_cb set error" << ret); + } + + if ((ret = bt_device_create_bond(device_addr) != BT_ERROR_NONE )) + { + ThrowMsg(Commons::PlatformException, "bt_device_create_bond error" << ret); + } + } + else + { + if ((ret = bt_device_set_bond_destroyed_cb (capi_callback_bt_device_bond_destroyed, (void*)this)) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::PlatformException, "bt_device_set_bond_created_cb set error" << ret); + } + + if ((ret = bt_device_destroy_bond (device_addr) != BT_ERROR_NONE )) + { + ThrowMsg(Commons::PlatformException, "bt_device_create_bond error" << ret); + } + + } + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + bt_device_unset_bond_destroyed_cb (); + event->setExceptionCode(ex.getCode()); + + + if (event->isCreateBonding()) + { + bt_device_unset_bond_created_cb(); + } + else + { + bt_device_unset_bond_destroyed_cb(); + } + + EventRequestReceiver::ManualAnswer(event); + } +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTSetNamePtr& event) +{ + LogDebug("Enter"); + try + { + std::string adapterName = event->getName(); + + + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + if (adapterName.length() == 0) + { + ThrowMsg(Commons::PlatformException, "set name parameter error"); + } + + if (bt_adapter_set_name_changed_cb(capi_callback_bt_name_changed, this) != BT_ERROR_NONE) + { + ThrowMsg(Commons::PlatformException, "callback set error"); + } + + if (bt_adapter_set_name(adapterName.c_str()) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::PlatformException, "set name error"); + } + + m_EventBTSetNamePtr = event; + event->switchToManualAnswer(); + + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } + +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTUnregisterRFCOMMServicePtr& event) +{ + LogDebug("Enter"); + + try + { + std::map::iterator it; + int socketFd = event->getUnregisterSocket(); + + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + + if (socketFd < 0) + { + ThrowMsg(Commons::UnsupportedException, "no service socket"); + } + + if (m_socketMap.size() != 0) + { + LogDebug("try to disconnect connected socket"); + for (it = m_socketMap.begin(); it != m_socketMap.end(); ++it) + { + bt_socket_disconnect_rfcomm((*it).second.connectedSocket); + } + } + else + { + LogDebug("there is no connected socket"); + } + + if (bt_socket_destroy_rfcomm(socketFd) != BT_ERROR_NONE) + { + ThrowMsg(Commons::UnsupportedException, "socket destroy error"); + } + event->setExceptionCode(Commons::ExceptionCodes::None); + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } + bt_adapter_unset_state_changed_cb(); + +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTStopDiscoveryPtr& event) +{ + LogDebug("Enter"); + + try + { + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + if (bt_adapter_stop_device_discovery() != BT_ERROR_NONE) + { + ThrowMsg(Commons::PlatformException, "device discovery stop fail"); + } + event->setExceptionCode(Commons::ExceptionCodes::None); + } + catch (const Commons::Exception &ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } + bt_adapter_unset_device_discovery_state_changed_cb(); +} + +} +} +} + diff --git a/src/platform/Tizen/Bluetooth/BluetoothAdapterManager.h b/src/platform/Tizen/Bluetooth/BluetoothAdapterManager.h new file mode 100755 index 0000000..b8fdb53 --- /dev/null +++ b/src/platform/Tizen/Bluetooth/BluetoothAdapterManager.h @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_PLATFORM_BLUETOOTH_ADAPTER_MANAGER_H_ +#define TIZENAPIS_PLATFORM_BLUETOOTH_ADAPTER_MANAGER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace TizenApis::Api; +using namespace TizenApis::Api::Bluetooth; + +namespace TizenApis { +namespace Platform { +namespace Bluetooth { + +class BluetoothAdapterManager : public Api::Bluetooth::IBluetoothAdapterManager +{ + friend class TizenApis::Api::Bluetooth::BluetoothFactory; + +public: + virtual ~BluetoothAdapterManager(); + virtual void setPowered(const EventBTSetPoweredPtr& event) ; + virtual void setVisible(const EventBTSetVisiblePtr& event) ; + virtual void getKownDevices(const EventBTGetKnownDevicesPtr& event) ; + virtual void getDevice(const EventBTGetDevicePtr& event) ; + virtual void createBonding(const EventBTCreateDestroyBondingPtr& event) ; + virtual void destroyBonding(const EventBTCreateDestroyBondingPtr& event) ; + virtual long registerRFCOMMServiceByUUID(const EventBTRegisterRFCOMMEmitterPtr& emitter, + std::string uuid, std::string name, unsigned short int security); + virtual void unregisterRFCOMMService(const EventBTUnregisterRFCOMMServicePtr& event); + virtual void discoveryDevicesEmitter(const EventBTOnDiscoveryDevicesEmitterPtr& emitter); + virtual void stopDiscovery(const EventBTStopDiscoveryPtr& event); + + virtual void setAdapterName(const EventBTSetNamePtr& event); + + virtual std::string getName(); + virtual std::string getAddress(); + virtual bool getPowered(); + virtual bool getVisibility(); + + void Init(); + void Test(); + bool canUseBluetooth(); + void setPoweredManualAnswer(); + void createBondingManualAnswer(unsigned short error, bt_device_info_s *device_info); + void destroyBondingManualAnswer(unsigned short error); + void getKnownDevicesManualAnswer(bt_device_info_s *discovery_info); + bool getDeviceManualAnswer(bt_device_info_s *device_info); + void discoveryDevicesCallbackEmit(unsigned short error, unsigned short state, bt_adapter_device_discovery_info_s *discovery_info); + void updateDevice(BluetoothDeviceData &device); + int findDevice(std::string address, BluetoothDeviceData &device); + void registerRFCOMMServiceByUUIDCallbackEmit(unsigned short error, bt_socket_connection_state_e connectionState, bt_socket_connection_s *connection); + void setAdapterNameManualAnswer(char* deviceName); +protected: + BluetoothAdapterManager(); + + virtual void OnRequestReceived(const EventBTSetPoweredPtr& event) ; + virtual void OnRequestReceived(const EventBTSetVisiblePtr& event) ; + virtual void OnRequestReceived(const EventBTGetKnownDevicesPtr& event) ; + virtual void OnRequestReceived(const EventBTGetDevicePtr& event) ; + virtual void OnRequestReceived(const EventBTCreateDestroyBondingPtr& event) ; + virtual void OnRequestReceived(const EventBTSetNamePtr& event); + virtual void OnRequestReceived(const EventBTUnregisterRFCOMMServicePtr& event); + virtual void OnRequestReceived(const EventBTStopDiscoveryPtr& event); + + +private: + static bool m_btPowered; + static bool m_btGetDeviceEvent; + static int m_currentServiceSocket; + std::string m_uuid; + std::string m_name; + std::map m_socketMap; + EventBTSetPoweredPtr m_EventBTSetPoweredPtr; + EventBTGetKnownDevicesPtr m_EventBTGetKnownDevicesPtr; + EventBTGetDevicePtr m_EventBTGetDevicePtr; + EventBTCreateDestroyBondingPtr m_EventBTCreateDestroyBondingPtr; + std::vector m_Devices; + EventBTRegisterRFCOMMEmitterPtr m_registerRFCOMMEmitter; + EventBTOnDiscoveryDevicesEmitterPtr m_discoverDevicesEmitter; + EventBTSetNamePtr m_EventBTSetNamePtr; + +}; + +} +} +} + +#endif diff --git a/src/platform/Tizen/Bluetooth/BluetoothDeviceManager.cpp b/src/platform/Tizen/Bluetooth/BluetoothDeviceManager.cpp new file mode 100755 index 0000000..1f9be0f --- /dev/null +++ b/src/platform/Tizen/Bluetooth/BluetoothDeviceManager.cpp @@ -0,0 +1,288 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "BluetoothDeviceManager.h" + +using namespace TizenApis::Api; +using namespace WrtDeviceApis; + + +namespace TizenApis { +namespace Platform { +namespace Bluetooth { + +using namespace Platform; + +BluetoothDeviceManager::BluetoothDeviceManager() +{ + m_serviceSocket= -1; + m_cancelRequest = false; +} + +BluetoothDeviceManager::~BluetoothDeviceManager() +{ +} + +namespace { +static void capi_callback_bt_socket_connection_state_changed(int result, bt_socket_connection_state_e connection_state, + bt_socket_connection_s *connection, void *user_data) +{ + + ((BluetoothDeviceManager*)user_data)->connectToServiceByUUIDManualAnswer(result, connection_state, connection); +} + + +static bool capi_callback_bt_device_bonded_device_find(bt_device_info_s *device_info, void *user_data) +{ + bool ret = true; + if( device_info != NULL ) + { + LogDebug("address " << device_info->remote_address << " " << device_info->remote_name); + ret = ((BluetoothDeviceManager*)user_data)->deviceFoundAnswer(device_info); + } + + return ret; +} + + +} + + + + +bool BluetoothDeviceManager::deviceFoundAnswer(bt_device_info_s *device_info) +{ + std::string remoteAddress = device_info->remote_address; + int index = 0; + + if (m_remoteAddress == remoteAddress) + { + LogDebug("Got Device : Major Class:" << device_info->bt_class.major_device_class); + LogDebug("Minor Class:" << device_info->bt_class.minor_device_class); + + m_remoteDevice.address = device_info->remote_address; + m_remoteDevice.name = device_info->remote_name; + + m_remoteDevice.btClass.major = device_info->bt_class.major_device_class; + m_remoteDevice.btClass.minor = device_info->bt_class.minor_device_class; + m_remoteDevice.btClass.majorServiceMask = device_info->bt_class.major_service_class_mask; + + + m_remoteDevice.isBonded = device_info->is_bonded; + m_remoteDevice.isConnected = device_info->is_connected; + m_remoteDevice.isTrusted = device_info->is_authorized; + + if (device_info->service_uuid != NULL) + { + for (index = 0; index < device_info->service_count; index++) + { + if (device_info->service_uuid[index] != NULL) + { + m_remoteDevice.uuids.push_back(device_info->service_uuid[index]); + } + } + } + else + { + LogDebug("service uuid is null"); + } + return false; + } + return true; +} +void BluetoothDeviceManager::connectToServiceByUUID(const EventBTConnectToServiceByUUIDPtr& event) +{ + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void BluetoothDeviceManager::setDevice(const BluetoothDeviceData device) +{ + m_device = device; +} + +BluetoothDeviceDataClass BluetoothDeviceManager::getClass() +{ + return m_device.btClass; +} + +void BluetoothDeviceManager::setNameProperty(const std::string name) +{ + LogDebug("Enter"); + m_device.name = name; +} + +void BluetoothDeviceManager::setAddressProperty(const std::string address) +{ + LogDebug("Enter"); + m_device.address = address; +} + +void BluetoothDeviceManager::setBondProperty(const bool bonded) +{ + LogDebug("Enter"); + m_device.isBonded = bonded; +} + +void BluetoothDeviceManager::setTrustProperty(const bool trusted) +{ + LogDebug("Enter"); + m_device.isTrusted = trusted; +} + +void BluetoothDeviceManager::setConnectProperty(const bool connected) +{ + LogDebug("Enter"); + m_device.isConnected= connected; +} + +void BluetoothDeviceManager::setUuidsProperty(const std::vector uuids) +{ + LogDebug("Enter"); + m_device.uuids = uuids; +} + +std::string BluetoothDeviceManager::getNameProperty(void) +{ + LogDebug("Enter" << m_device.name); + return m_device.name; +} +std::string BluetoothDeviceManager::getAddressProperty(void) +{ + LogDebug("Enter" << m_device.address); + return m_device.address; +} +bool BluetoothDeviceManager::getBondProperty(void) +{ + LogDebug("Enter" << m_device.isBonded); + return m_device.isBonded; +} +bool BluetoothDeviceManager::getTrustProperty(void) +{ + LogDebug("Enter" << m_device.isTrusted); + return m_device.isTrusted; +} +bool BluetoothDeviceManager::getConnectProperty(void) +{ + LogDebug("Enter" << m_device.isConnected); + return m_device.isConnected; +} +std::vector BluetoothDeviceManager::getUuidsProperty(void) +{ + LogDebug("Enter"); + return m_device.uuids; +} + +void BluetoothDeviceManager::cancelConnectToServiceByUUID() +{ + m_cancelRequest = true; +} + +void BluetoothDeviceManager::connectToServiceByUUIDManualAnswer(unsigned short error, + bt_socket_connection_state_e connectionState, bt_socket_connection_s *connection) + +{ + LogDebug("Enter"); + + if (error == BT_ERROR_NONE) + { + if (m_cancelRequest) + { + if (connection->socket_fd > 0) + { + LogDebug("Cancel connect, try to disconnect"); + bt_socket_disconnect_rfcomm(connection->socket_fd); + bt_socket_unset_connection_state_changed_cb(); + } + return; + } + + BluetoothSocketData socketData = m_EventBTConnectToServiceByUUIDPtr->getSocketData(); + m_remoteAddress = connection->remote_address; + LogDebug("address" << m_remoteAddress << "-" << socketData.peerDevice.address); + + if ((bt_adapter_foreach_bonded_device(capi_callback_bt_device_bonded_device_find, (void*)this)) != BT_ERROR_NONE) + { + m_remoteDevice.address = m_remoteAddress; + } + + m_remoteDevice.isConnected = true; + socketData.peerDevice = m_remoteDevice; + socketData.connectedSocket = connection->socket_fd; + socketData.protocol = PROTOCOL_TYPE_RFCOMM_VALUE_INT; + socketData.state = SOCKET_STATE_OPEN_VALUE_INT; + + if (connection->local_role == BT_SOCKET_SERVER) + { + socketData.isServer = true; + } + else + { + socketData.isServer = false; + } + + m_EventBTConnectToServiceByUUIDPtr->setExceptionCode(Commons::ExceptionCodes::None); + m_EventBTConnectToServiceByUUIDPtr->setSocketData(socketData); + } + else + { + m_EventBTConnectToServiceByUUIDPtr->setExceptionCode(Commons::ExceptionCodes::PlatformException); + + } + bt_socket_unset_connection_state_changed_cb(); + EventRequestReceiver::ManualAnswer(m_EventBTConnectToServiceByUUIDPtr); +} + +void BluetoothDeviceManager::OnRequestReceived(const EventBTConnectToServiceByUUIDPtr& event) +{ + LogDebug("Enter"); + + unsigned short error = Commons::ExceptionCodes::UnknownException; + m_EventBTConnectToServiceByUUIDPtr = event; + event->switchToManualAnswer(); + BluetoothSocketData socketData = event->getSocketData(); + socketData.peerDevice = m_device; + event->setSocketData(socketData); + m_cancelRequest = false; + + try + { + if( bt_socket_set_connection_state_changed_cb(capi_callback_bt_socket_connection_state_changed, this) != BT_ERROR_NONE ) + { + error = Commons::ExceptionCodes::UnknownException; + ThrowMsg(Commons::UnknownException, "service call back set error"); + } + + if( bt_socket_connect_rfcomm(socketData.peerDevice.address.data(), + socketData.uuid.data()) != BT_ERROR_NONE ) + { + error = Commons::ExceptionCodes::UnknownException; + ThrowMsg(Commons::UnknownException, "connect error"); + } + event->setCancelAllowed(true); + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + bt_socket_unset_connection_state_changed_cb(); + EventRequestReceiver::ManualAnswer(event); + } + +} +} +} +} diff --git a/src/platform/Tizen/Bluetooth/BluetoothDeviceManager.h b/src/platform/Tizen/Bluetooth/BluetoothDeviceManager.h new file mode 100644 index 0000000..1221113 --- /dev/null +++ b/src/platform/Tizen/Bluetooth/BluetoothDeviceManager.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef TIZENAPIS_TIZEN_BLUETOOTH_DEVICE_MANAGER_H_ +#define TIZENAPIS_TIZEN_BLUETOOTH_DEVICE_MANAGER_H_ + +#include +#include +#include +#include +#include + +using namespace TizenApis::Api; +using namespace TizenApis::Api::Bluetooth; + +namespace TizenApis { +namespace Platform { +namespace Bluetooth { + +class BluetoothDeviceManager : public Api::Bluetooth::IBluetoothDeviceManager +{ + friend class TizenApis::Api::Bluetooth::BluetoothFactory; + +private: + BluetoothDeviceData m_device; + BluetoothDeviceData m_remoteDevice; + int m_serviceSocket; + std::string m_remoteAddress; + EventBTConnectToServiceByUUIDPtr m_EventBTConnectToServiceByUUIDPtr; + bool m_cancelRequest; +public: + bool deviceFoundAnswer(bt_device_info_s *device_info); + void connectToServiceByUUIDManualAnswer(unsigned short error, + bt_socket_connection_state_e connectionState, bt_socket_connection_s *connection); + + virtual ~BluetoothDeviceManager(); + virtual void connectToServiceByUUID(const EventBTConnectToServiceByUUIDPtr& event) ; + + virtual void setNameProperty(const std::string name) ; + virtual void setAddressProperty(const std::string address) ; + virtual void setBondProperty(const bool bonded) ; + virtual void setTrustProperty(const bool trused) ; + virtual void setConnectProperty(const bool connected) ; + virtual void setUuidsProperty(const std::vector uuids) ; + virtual void cancelConnectToServiceByUUID(); + + virtual std::string getNameProperty(void) ; + virtual std::string getAddressProperty(void) ; + virtual bool getBondProperty(void) ; + virtual bool getTrustProperty(void) ; + virtual bool getConnectProperty(void) ; + virtual std::vector getUuidsProperty(void) ; + virtual void setDevice(const BluetoothDeviceData device) ; + virtual BluetoothDeviceDataClass getClass(); +protected: + BluetoothDeviceManager(); + virtual void OnRequestReceived(const EventBTConnectToServiceByUUIDPtr& event) ; + +}; + +} +} +} + +#endif + diff --git a/src/platform/Tizen/Bluetooth/BluetoothManager.cpp b/src/platform/Tizen/Bluetooth/BluetoothManager.cpp new file mode 100755 index 0000000..d97e143 --- /dev/null +++ b/src/platform/Tizen/Bluetooth/BluetoothManager.cpp @@ -0,0 +1,1158 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "BluetoothAdapterManager.h" +#include +#include + +using namespace TizenApis::Api; +using namespace WrtDeviceApis; +using namespace DPL; + +namespace TizenApis { +namespace Platform { +namespace Bluetooth { + +bool BluetoothAdapterManager::m_btPowered = false; +bool BluetoothAdapterManager::m_btGetDeviceEvent = false; +int BluetoothAdapterManager::m_currentServiceSocket = -1; + + +namespace { + +static void capi_callback_bt_name_changed(char *device_name, void *user_data) +{ + ((BluetoothAdapterManager*)user_data)->setAdapterNameManualAnswer(device_name); +} + + + + +static void capi_callback_bt_state_changed(int result, bt_adapter_state_e adapter_state, void* user_data) +{ + if( result == BT_ERROR_NONE ) + { + LogDebug("State Changed" << adapter_state); + ((BluetoothAdapterManager*)user_data)->setPoweredManualAnswer(); + } + else + { + LogDebug("Error"); + } +} + + +static void capi_callback_bt_visibility_changed(int result, bt_adapter_visibility_mode_e visibility, void *user_data) +{ + if (result == BT_ERROR_NONE) + { + LogDebug("Visibility changed" << visibility); + ((BluetoothAdapterManager*)user_data)->setVisibleManualAnswer(); + } + else + { + LogDebug("Error"); + } +} + +static void capi_callback_bt_discovery_state_changed(int result, + bt_adapter_device_discovery_state_e discovery_state, bt_adapter_device_discovery_info_s *discovery_info, void *user_data) +{ + LogDebug("Discovery state" << discovery_state); + if (discovery_state == BT_ADAPTER_DEVICE_DISCOVERY_FOUND && discovery_info != NULL) + { + LogDebug("found device" << discovery_info->remote_name << " " << discovery_info->remote_address); + } + + LogDebug("Discovery state" << discovery_state); + ((BluetoothAdapterManager*)user_data)->discoveryDevicesCallbackEmit(result, discovery_state, discovery_info); + +} + + +static bool capi_callback_bt_adapter_bonded_device(bt_device_info_s *device_info, void *user_data) +{ + if( device_info != NULL ) + { + LogDebug("address " << device_info->remote_address << " " << device_info->remote_name); + ((BluetoothAdapterManager*)user_data)->getKnownDevicesManualAnswer (device_info); + } + + return true; +} + +static bool capi_callback_bt_adapter_bonded_device_find(bt_device_info_s *device_info, void *user_data) +{ + bool ret = true; + if( device_info != NULL ) + { + LogDebug("address " << device_info->remote_address << " " << device_info->remote_name); + ret = ((BluetoothAdapterManager*)user_data)->getDeviceManualAnswer (device_info); + } + + return ret;; +} + + +static void capi_callback_bt_device_bond_created(int result, bt_device_info_s *device_info, void *user_data) +{ + ((BluetoothAdapterManager*)user_data)->createBondingManualAnswer(result, device_info); +} + +static void capi_callback_bt_device_bond_destroyed(int result, char* remote_address, void *user_data) +{ + ((BluetoothAdapterManager*)user_data)->destroyBondingManualAnswer(result); +} + +static void capi_callback_bt_socket_connection_state_changed(int result, bt_socket_connection_state_e connection_state, + bt_socket_connection_s *connection, void *user_data) +{ + LogDebug("OK"); + + ((BluetoothAdapterManager*)user_data)->registerRFCOMMServiceByUUIDCallbackEmit(result, connection_state, connection); +} +} + +BluetoothAdapterManager::BluetoothAdapterManager() +{ + LogDebug("Enter"); + Init(); + m_btPowered = canUseBluetooth(); +} + +BluetoothAdapterManager::~BluetoothAdapterManager() +{ + LogDebug("Enter"); +} + +void BluetoothAdapterManager::Init() +{ + LogDebug("Enter"); + + bt_initialize(); +} + +bool BluetoothAdapterManager::canUseBluetooth() +{ + bt_adapter_state_e state; + int ret; + + ret = bt_adapter_get_state(&state); + + if (ret == BT_ERROR_NONE && state == BT_ADAPTER_ENABLED) + { + return true; + } + else + { + return false; + } +} + + +std::string BluetoothAdapterManager::getName() +{ + char* name = NULL; + std::string str = ""; + + if (bt_adapter_get_name(&name) == BT_ERROR_NONE) + { + LogDebug("OK"); + + if (name != NULL) + { + LogDebug("Set"); + str = name; + free(name); + } + } + return str; +} + +std::string BluetoothAdapterManager::getAddress() +{ + char* address = NULL; + std::string str = ""; + + if (bt_adapter_get_address(&address) == BT_ERROR_NONE) + { + LogDebug("OK"); + if (address != NULL) + { + LogDebug("Set"); + str = address; + free(address); + } + } + return str; + +} + +bool BluetoothAdapterManager::getPowered() +{ + bt_adapter_state_e state; + + if (bt_adapter_get_state(&state) == BT_ERROR_NONE) + { + if (state == BT_ADAPTER_ENABLED) + { + return true; + } + } + + return false; +} + +bool BluetoothAdapterManager::getVisibility() +{ + bt_adapter_visibility_mode_e mode; + + if (bt_adapter_get_visibility(&mode) == BT_ERROR_NONE) + { + if (mode != BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE) + { + return true; + } + } + return false; +} + +void BluetoothAdapterManager::setPowered(const EventBTSetPoweredPtr& event) +{ + LogDebug("Enter"); + + if (event->isEnableRequested()) + { + Init(); + } + + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::setPoweredManualAnswer() +{ + LogDebug("Enter"); + + m_btPowered = canUseBluetooth(); + bt_adapter_unset_state_changed_cb(); + + if (m_EventBTSetPoweredPtr->isEnableRequested()) + { + if (m_btPowered == true) + { + m_EventBTSetPoweredPtr->setExceptionCode(Commons::ExceptionCodes::None); + } + else + { + m_EventBTSetPoweredPtr->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + } + else + { + if (m_btPowered == false) + { + m_EventBTSetPoweredPtr->setExceptionCode(Commons::ExceptionCodes::None); + } + else + { + m_EventBTSetPoweredPtr->setExceptionCode(Commons::ExceptionCodes::PlatformException); + + } + } + EventRequestReceiver::ManualAnswer(m_EventBTSetPoweredPtr); +} + +void BluetoothAdapterManager::setVisible(const EventBTSetVisiblePtr& event) +{ + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::setVisibleManualAnswer() +{ + LogDebug("Enter"); + + bt_adapter_unset_visibility_mode_changed_cb(); + LogDebug("bt_adapter_unset_visibility_mode_changed_cb"); + + m_EventBTSetVisiblePtr->setExceptionCode(Commons::ExceptionCodes::None); + EventRequestReceiver::ManualAnswer(m_EventBTSetVisiblePtr); +} + +void BluetoothAdapterManager::discoveryDevicesEmitter(const EventBTOnDiscoveryDevicesEmitterPtr& emitter) + +{ + LogDebug("Enter"); + + int ret = 0; + + m_discoverDevicesEmitter = emitter; + + try + { + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + if ((ret = bt_adapter_set_device_discovery_state_changed_cb(capi_callback_bt_discovery_state_changed, + (void*)this))!= BT_ERROR_NONE) + { + ThrowMsg(Commons::UnknownException, "platform exception error" << ret); + } + + if ((ret = bt_adapter_start_device_discovery() != BT_ERROR_NONE)) + { + ThrowMsg(Commons::UnknownException, "device discovery fail" << ret); + } + LogDebug("OK Discovery Start"); + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + bt_adapter_unset_device_discovery_state_changed_cb(); + + EventBTOnDiscoveryDevicesPtr event(new EventBTOnDiscoveryDevices()); + event->setExceptionCode(ex.getCode()); + m_discoverDevicesEmitter->emit(event); + } +} + + +void BluetoothAdapterManager::discoveryDevicesCallbackEmit(unsigned short error, unsigned short state, + bt_adapter_device_discovery_info_s *discovery_info) + +{ + BluetoothDeviceData device; + EventBTOnDiscoveryDevicesPtr event(new EventBTOnDiscoveryDevices()); + unsigned int index = 0; + + try + { + if (discovery_info != NULL) + { + device.address = discovery_info->remote_address; + device.name = discovery_info->remote_name; + device.btClass.major = discovery_info->bt_class.major_device_class; + device.btClass.minor = discovery_info->bt_class.minor_device_class; + device.btClass.majorServiceMask = discovery_info->bt_class.major_service_class_mask; + } + + switch(state) + { + case BT_ADAPTER_DEVICE_DISCOVERY_STARTED: + event->setDiscoveryState(EventBTOnDiscoveryDevices::STARTED); + break; + case BT_ADAPTER_DEVICE_DISCOVERY_FOUND: + event->setDiscoveryState(EventBTOnDiscoveryDevices::DISCOVERYING); + event->addDevice(device); + m_Devices.push_back(device); + break; + case BT_ADAPTER_DEVICE_DISCOVERY_FINISHED: + event->setDiscoveryState(EventBTOnDiscoveryDevices::FINISHED); + + for (index = 0; index < m_Devices.size(); index++) + { + event->addDevice(m_Devices[index]); + } + bt_adapter_unset_device_discovery_state_changed_cb(); + break; + default: + ThrowMsg(Commons::UnknownException, "device discovery fail"); + } + event->setExceptionCode(Commons::ExceptionCodes::None); + m_discoverDevicesEmitter->emit(event); + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + bt_adapter_unset_device_discovery_state_changed_cb(); + m_discoverDevicesEmitter->emit(event); + } +} + +void BluetoothAdapterManager::getKownDevices(const EventBTGetKnownDevicesPtr& event) +{ + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::updateDevice(BluetoothDeviceData &device) +{ + unsigned int i = 0; + LogDebug("Enter"); + + for (i = 0; i < m_Devices.size(); i++) + { + if (device.address == m_Devices[i].address && + device.name == m_Devices[i].name) + { + m_Devices[i].isBonded = device.isBonded; + m_Devices[i].isConnected = device.isConnected; + m_Devices[i].isTrusted = device.isTrusted; + m_Devices[i].btClass = device.btClass; + m_Devices[i].uuids = device.uuids; + + } + } + + if (i == m_Devices.size()) + { + m_Devices.push_back(device); + } +} + +int BluetoothAdapterManager::findDevice(std::string address, BluetoothDeviceData& device) +{ + unsigned int i = 0; + + for (i = 0; i < m_Devices.size(); i++) + { + if (address == m_Devices[i].address) + { + device = m_Devices[i]; + return BT_ERROR_NONE; + } + } + return BT_ERROR_OPERATION_FAILED; +} + +void BluetoothAdapterManager::getKnownDevicesManualAnswer(bt_device_info_s *device_info) +{ + LogDebug("Enter"); + + BluetoothDeviceData device; + int index = 0; + + if (device_info != NULL) + { + + device.address = device_info->remote_address; + device.name = device_info->remote_name; + + device.btClass.major = device_info->bt_class.major_device_class; + device.btClass.minor = device_info->bt_class.minor_device_class; + device.btClass.majorServiceMask = device_info->bt_class.major_service_class_mask; + + device.isBonded = device_info->is_bonded; + device.isConnected = device_info->is_connected; + device.isTrusted = device_info->is_authorized; + + if (device_info->service_uuid != NULL) + { + for (index = 0; index < device_info->service_count; index++) + { + if (device_info->service_uuid[index] != NULL) + { + device.uuids.push_back(device_info->service_uuid[index]); + } + } + } + else + { + LogDebug("uuid is null"); + } + updateDevice(device); + m_EventBTGetKnownDevicesPtr->addDevice(device); + } + +} + +void BluetoothAdapterManager::getDevice(const EventBTGetDevicePtr& event) +{ + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + + +bool BluetoothAdapterManager::getDeviceManualAnswer(bt_device_info_s *device_info) +{ + std::string address = ""; + + if (device_info != NULL) + { + address = device_info->remote_address; + } + + BluetoothDeviceData device; + int index = 0; + + device.address = device_info->remote_address; + device.name = device_info->remote_name; + + device.btClass.major = device_info->bt_class.major_device_class; + device.btClass.minor = device_info->bt_class.minor_device_class; + device.btClass.majorServiceMask = device_info->bt_class.major_service_class_mask; + + + device.isBonded = device_info->is_bonded; + device.isConnected = device_info->is_connected; + device.isTrusted = device_info->is_authorized; + + LogDebug("Enter Found " << device.address << " " << device.name << " " << device.btClass.major << " " << device.btClass.minor); + + if (device_info->service_uuid != NULL) + { + + for (index = 0; index < device_info->service_count; index++) + { + if (device_info->service_uuid[index] != NULL) + { + device.uuids.push_back(device_info->service_uuid[index]); + } + } + } + else + { + LogDebug("service uuid null"); + } + + if (m_btGetDeviceEvent) + { + LogDebug("Enter - getDeviceManualAnswer" << address << ":" << m_EventBTGetDevicePtr->getAddress()); + + if (address == m_EventBTGetDevicePtr->getAddress()) + { + updateDevice(device); + m_EventBTGetDevicePtr->setDevice(device); + return false; + } + } + else + { + updateDevice(device); + } + + return true; +} + + + +void BluetoothAdapterManager::createBonding(const EventBTCreateDestroyBondingPtr& event) +{ + LogDebug("Post Event EventBTCreateDestroyBonding"); + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::createBondingManualAnswer(unsigned short error, bt_device_info_s *device_info) +{ + int index = 0; + + if (error == BT_ERROR_NONE) + { + LogDebug("createBondingManualAnswer"); + + BluetoothDeviceData device; + device.address = device_info->remote_address; + device.name = device_info->remote_name; + device.isBonded = device_info->is_bonded; + device.isConnected = device_info->is_connected; + device.isTrusted = device_info->is_authorized; + + if (device_info->service_uuid != NULL) + { + for (index = 0; index < device_info->service_count; index++) + { + if (device_info->service_uuid[index] != NULL) + { + device.uuids.push_back(device_info->service_uuid[index]); + } + } + } + else + { + LogDebug("service uuid null"); + } + m_EventBTCreateDestroyBondingPtr->setExceptionCode(Commons::ExceptionCodes::None); + m_EventBTCreateDestroyBondingPtr->setDevice(device); + } + else + { + m_EventBTCreateDestroyBondingPtr->setExceptionCode(Commons::ExceptionCodes::UnknownException); + } + bt_device_unset_bond_created_cb(); + EventRequestReceiver::ManualAnswer(m_EventBTCreateDestroyBondingPtr); +} + + + +void BluetoothAdapterManager::destroyBonding(const EventBTCreateDestroyBondingPtr& event) +{ + LogDebug("Post Event EventBTCreateDestroyBonding"); + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::destroyBondingManualAnswer(unsigned short error) +{ + if (error == BT_ERROR_NONE) + { + m_EventBTCreateDestroyBondingPtr->setExceptionCode(Commons::ExceptionCodes::None); + } + else + { + m_EventBTCreateDestroyBondingPtr->setExceptionCode(Commons::ExceptionCodes::UnknownException); + } + bt_device_unset_bond_destroyed_cb(); + EventRequestReceiver::ManualAnswer(m_EventBTCreateDestroyBondingPtr); +} + + +void BluetoothAdapterManager::registerRFCOMMServiceByUUIDCallbackEmit(unsigned short error, + bt_socket_connection_state_e connectionState, bt_socket_connection_s *connection) +{ + LogDebug("OK"); + + EventBTRegisterRFCOMMPtr event(new EventBTRegisterRFCOMM()); + bt_socket_unset_connection_state_changed_cb() ; + int ret = 0; + + if (error == BT_ERROR_NONE) + { + if (connectionState == BT_SOCKET_CONNECTED) + { + BluetoothDeviceData deviceData; + BluetoothSocketData socketData; + std::map::iterator it; + + event->setConnectionState(EventBTRegisterRFCOMM::REGISTER_CONNECTED); + + m_btGetDeviceEvent = false; + + if ((ret = bt_adapter_foreach_bonded_device(capi_callback_bt_adapter_bonded_device_find, (void*)this)) == BT_ERROR_NONE) + { + findDevice(connection->remote_address, deviceData); + } + + deviceData.isConnected = true; + + if (connection->local_role == BT_SOCKET_SERVER) + { + socketData.isServer = true; + } + else + { + socketData.isServer = false; + } + + socketData.protocol = PROTOCOL_TYPE_RFCOMM_VALUE_INT; + + socketData.connectedSocket = connection->socket_fd; + socketData.registeredSocket = m_currentServiceSocket; + socketData.state = SOCKET_STATE_OPEN_VALUE_INT; + socketData.uuid = m_uuid; + socketData.peerDevice = deviceData; + + if (m_socketMap.find(deviceData.address) != m_socketMap.end()) + { + LogDebug("Found same device, remove!"); + m_socketMap.erase(it); + } + + m_socketMap[deviceData.address] = socketData; + event->setSocketData(socketData); + event->setExceptionCode(Commons::ExceptionCodes::None); + } + else + { + event->setConnectionState(EventBTRegisterRFCOMM::REGISTER_DISCONNECTED); + } + } + else + { + event->setExceptionCode(Commons::ExceptionCodes::UnknownException); + } + m_registerRFCOMMEmitter->emit(event); + + +} +long BluetoothAdapterManager::registerRFCOMMServiceByUUID(const EventBTRegisterRFCOMMEmitterPtr& emitter, + std::string uuid, std::string name, unsigned short int security) +{ + LogDebug("EventBTRegisterRFCOMMPtr"); + + int ret = 0; + m_registerRFCOMMEmitter = emitter; + m_uuid = uuid; + m_name = name; + + try + { + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + if (getVisibility() == false) + { + ThrowMsg(Commons::UnknownException, "please set visivility"); + } + + if((ret = bt_socket_create_rfcomm(uuid.data(), &m_currentServiceSocket)) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "service socket creation error" << ret); + } + + if( bt_socket_set_connection_state_changed_cb(capi_callback_bt_socket_connection_state_changed, this) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "unkown platfrom exception"); + } + + if( bt_socket_listen_and_accept_rfcomm(m_currentServiceSocket, 1) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "service socket register error"); + } + EventBTRegisterRFCOMMPtr event(new EventBTRegisterRFCOMM()); + event->setConnectionState(EventBTRegisterRFCOMM::REGISTER_SUCCESS); + event->setExceptionCode(Commons::ExceptionCodes::None); + m_registerRFCOMMEmitter->emit(event); + + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + EventBTRegisterRFCOMMPtr event(new EventBTRegisterRFCOMM()); + event->setExceptionCode(ex.getCode()); + m_registerRFCOMMEmitter->emit(event); + } + return m_currentServiceSocket; +} + +void BluetoothAdapterManager::unregisterRFCOMMService(const EventBTUnregisterRFCOMMServicePtr& event) +{ + LogDebug("EventBTUnregisterRFCOMMServicePtr"); + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::setAdapterName(const EventBTSetNamePtr& event) +{ + LogDebug("EventBTSetNamePtr"); + EventRequestReceiver::PostRequest(event); +} + +void BluetoothAdapterManager::setAdapterNameManualAnswer(char* deviceName) +{ + LogDebug("Enter"); + + if (deviceName != NULL) + { + if (strcmp(deviceName, m_EventBTSetNamePtr->getName().c_str()) != 0) + { + m_EventBTSetNamePtr->setExceptionCode(Commons::ExceptionCodes::UnknownException); + } + else + { + m_EventBTSetNamePtr->setExceptionCode(Commons::ExceptionCodes::None); + } + } + else + { + m_EventBTSetNamePtr->setExceptionCode(Commons::ExceptionCodes::UnknownException); + } + + EventRequestReceiver::ManualAnswer(m_EventBTSetNamePtr); +} + + + +void BluetoothAdapterManager::stopDiscovery(const EventBTStopDiscoveryPtr& event) +{ + LogDebug("EventBTStopDiscoveryPtr"); + EventRequestReceiver::PostRequest(event); + +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTSetPoweredPtr& event) +{ + int ret = 0; + + try + { + event->switchToManualAnswer(); + m_EventBTSetPoweredPtr = event; + + if( bt_adapter_set_state_changed_cb(capi_callback_bt_state_changed, (void*)this) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + + if (event->isEnableRequested()) + { + ret = bt_adapter_enable(); + + switch(ret) + { + case BT_ERROR_NONE: + return; + case BT_ERROR_ALREADY_DONE: + event->setExceptionCode(Commons::ExceptionCodes::None); + m_btPowered = canUseBluetooth(); + bt_adapter_unset_state_changed_cb(); + EventRequestReceiver::ManualAnswer(event); + break; + case BT_ERROR_NOT_INITIALIZED: + ThrowMsg(Commons::UnknownException, "bt is not initialized"); + break; + case BT_ERROR_RESOURCE_BUSY: + default: + ThrowMsg(Commons::SecurityException, "bt is busy"); + break; + } + } + else + { + LogDebug("Disable"); + ret = bt_adapter_disable(); + + if (ret == BT_ERROR_NONE) + { + return; + } + ThrowMsg(Commons::UnknownException, "can not disable bt"); + } + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + bt_adapter_unset_state_changed_cb(); + EventRequestReceiver::ManualAnswer(event); + } +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTSetVisiblePtr& event) +{ + LogDebug("Enter"); + int ret = 0; + bt_adapter_visibility_mode_e visibility_mode = BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE; + bt_adapter_visibility_mode_e current_visibility = BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE; + + try + { + m_EventBTSetVisiblePtr = event; + event->switchToManualAnswer(); + + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + if (event->isVisibleRequested()) + { + if (event->getTimeout() == 0) + { + visibility_mode = BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE; + } + else + { + visibility_mode = BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE; + } + } + else + { + visibility_mode = BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE; + + } + + if (bt_adapter_get_visibility(¤t_visibility) != BT_ERROR_NONE) + { + ThrowMsg(Commons::UnknownException, "get visibility error" << ret); + } + + + if (current_visibility == visibility_mode) + { + LogDebug("already same visiblity"); + event->setExceptionCode(Commons::ExceptionCodes::None); + EventRequestReceiver::ManualAnswer(event); + return; + } + + if((ret = bt_adapter_set_visibility_mode_changed_cb(capi_callback_bt_visibility_changed, (void*)this)) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error" << ret); + } + + LogDebug("bt_adapter_set_visibility " << visibility_mode << " " << event->getTimeout()); + + if ((ret = bt_adapter_set_visibility(visibility_mode, event->getTimeout()) != BT_ERROR_NONE)) + { + ThrowMsg(Commons::UnknownException, "set visibility error" << ret); + } + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + bt_adapter_unset_visibility_mode_changed_cb(); + EventRequestReceiver::ManualAnswer(event); + } +} + + +void BluetoothAdapterManager::OnRequestReceived(const EventBTGetKnownDevicesPtr& event) +{ + LogDebug("EventBTGetKnownDevicesPtr Enter"); + + int ret = 0; + + try + { + m_EventBTGetKnownDevicesPtr = event; + + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + if ((ret = bt_adapter_foreach_bonded_device(capi_callback_bt_adapter_bonded_device, (void*)this))!= BT_ERROR_NONE) + { + ThrowMsg(Commons::UnknownException, "bt_adapter_foreach_bonded_device" << ret); + } + + LogDebug("Get Konwn device"); + + event->setExceptionCode(Commons::ExceptionCodes::None); + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTGetDevicePtr& event) +{ + LogDebug("EventBTGetDevicePtr Enter"); + + int ret = 0; + + try + { + m_EventBTGetDevicePtr = event; + + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + m_btGetDeviceEvent = true; + + if ((ret = bt_adapter_foreach_bonded_device(capi_callback_bt_adapter_bonded_device_find, (void*)this))!= BT_ERROR_NONE) + { + ThrowMsg(Commons::UnknownException, "bt_adapter_foreach_bonded_device" << ret); + } + m_btGetDeviceEvent = false; + + LogDebug("EventBTGetDevicePtr"); + event->setExceptionCode(Commons::ExceptionCodes::None); + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTCreateDestroyBondingPtr& event) +{ + LogDebug("Enter"); + + int ret = 0; + const char *device_addr = (event->getAddress()).data(); + + try + { + m_EventBTCreateDestroyBondingPtr = event; + event->switchToManualAnswer(); + + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + + if ((event->getAddress()).length() == 0) + { + ThrowMsg(Commons::PlatformException, "address error" << ret); + } + + + if (event->isCreateBonding()) + { + + if ((ret = bt_device_set_bond_created_cb(capi_callback_bt_device_bond_created, (void*)this)) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::PlatformException, "bt_device_set_bond_created_cb set error" << ret); + } + + if ((ret = bt_device_create_bond(device_addr) != BT_ERROR_NONE )) + { + ThrowMsg(Commons::PlatformException, "bt_device_create_bond error" << ret); + } + } + else + { + if ((ret = bt_device_set_bond_destroyed_cb (capi_callback_bt_device_bond_destroyed, (void*)this)) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::PlatformException, "bt_device_set_bond_created_cb set error" << ret); + } + + if ((ret = bt_device_destroy_bond (device_addr) != BT_ERROR_NONE )) + { + ThrowMsg(Commons::PlatformException, "bt_device_create_bond error" << ret); + } + + } + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + bt_device_unset_bond_destroyed_cb (); + event->setExceptionCode(ex.getCode()); + + + if (event->isCreateBonding()) + { + bt_device_unset_bond_created_cb(); + } + else + { + bt_device_unset_bond_destroyed_cb(); + } + + EventRequestReceiver::ManualAnswer(event); + } +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTSetNamePtr& event) +{ + LogDebug("Enter"); + try + { + std::string adapterName = event->getName(); + + + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + if (adapterName.length() == 0) + { + ThrowMsg(Commons::PlatformException, "set name parameter error"); + } + + if (bt_adapter_set_name_changed_cb(capi_callback_bt_name_changed, this) != BT_ERROR_NONE) + { + ThrowMsg(Commons::PlatformException, "callback set error"); + } + + if (bt_adapter_set_name(adapterName.c_str()) != BT_ERROR_NONE ) + { + ThrowMsg(Commons::PlatformException, "set name error"); + } + + m_EventBTSetNamePtr = event; + event->switchToManualAnswer(); + + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } + +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTUnregisterRFCOMMServicePtr& event) +{ + LogDebug("Enter"); + + try + { + std::map::iterator it; + int socketFd = event->getUnregisterSocket(); + + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + + if (socketFd < 0) + { + ThrowMsg(Commons::UnsupportedException, "no service socket"); + } + + if (m_socketMap.size() != 0) + { + LogDebug("try to disconnect connected socket"); + for (it = m_socketMap.begin(); it != m_socketMap.end(); ++it) + { + bt_socket_disconnect_rfcomm((*it).second.connectedSocket); + } + } + else + { + LogDebug("there is no connected socket"); + } + + if (bt_socket_destroy_rfcomm(socketFd) != BT_ERROR_NONE) + { + ThrowMsg(Commons::UnsupportedException, "socket destroy error"); + } + event->setExceptionCode(Commons::ExceptionCodes::None); + } + catch (const Commons::Exception& ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } + bt_adapter_unset_state_changed_cb(); + +} + +void BluetoothAdapterManager::OnRequestReceived(const EventBTStopDiscoveryPtr& event) +{ + LogDebug("Enter"); + + try + { + if (m_btPowered == false) + { + ThrowMsg(Commons::UnsupportedException, "bluetooth adpater off"); + } + + if (bt_adapter_stop_device_discovery() != BT_ERROR_NONE) + { + ThrowMsg(Commons::PlatformException, "device discovery stop fail"); + } + bt_adapter_unset_device_discovery_state_changed_cb(); + event->setExceptionCode(Commons::ExceptionCodes::None); + } + catch (const Commons::Exception &ex) + { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } +} + +} +} +} + diff --git a/src/platform/Tizen/Bluetooth/BluetoothSocketManager.cpp b/src/platform/Tizen/Bluetooth/BluetoothSocketManager.cpp new file mode 100755 index 0000000..ae77c9c --- /dev/null +++ b/src/platform/Tizen/Bluetooth/BluetoothSocketManager.cpp @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "BluetoothSocketManager.h" +#include + +using namespace TizenApis::Api; + + +namespace TizenApis { +namespace Platform { +namespace Bluetooth { + +using namespace Platform; + +BluetoothSocketManager::BluetoothSocketManager() +{ + LogDebug("Enter"); + m_socketData.connectedSocket = -1; + m_socketData.registeredSocket = -1; +} + +BluetoothSocketManager::~BluetoothSocketManager() +{ + LogDebug("Enter"); +} + + +namespace { + +static void capi_callback_bt_connection_state_changed(int result, bt_socket_connection_state_e connection_state, + bt_socket_connection_s *connection, void *user_data) +{ + LogDebug("OK"); + ((BluetoothSocketManager*)(user_data))->connectionStateChangedEmit(result, connection_state, connection); +} + +static void capi_callback_bt_data_received(bt_socket_received_data_s *data, void *user_data) +{ + ((BluetoothSocketManager*)(user_data))->setDataReceivedEmit(data); +} + +} + +void BluetoothSocketManager::setReadData(EventBTReadDataType readData) +{ + DPL::Mutex::ScopedLock lock(&m_mtx); + m_readData = readData; +} + +void BluetoothSocketManager::setDataReceivedEmit(bt_socket_received_data_s *data) +{ + assert(m_socketData.connectedSocket == data->socket_fd); + assert(data->data != NULL); + assert(data->data_size != 0); + + + LogDebug("OK" << data->data[0] << data->data[1] << " :" << data->data_size); + + DPL::Mutex::ScopedLock lock(&m_mtx); + + EventBTSocketNotificationPtr event(new EventBTSocketNotification()); + event->setSocketData(m_socketData); + event->setReadData(data->data, data->data_size); + event->setConnectionState(EventBTSocketNotification::DATARECEIVED); + m_EventBTSocketNotificationEmitterPtr->emit(event); +} + +void BluetoothSocketManager::connectionStateChangedEmit(int result, + bt_socket_connection_state_e connection_state, bt_socket_connection_s *connection) +{ + assert(m_socketData.connectedSocket == connection->socket_fd); + assert(strcmp(m_socketData.peerDevice.address.data(), connection->remote_address) == 0); + + LogDebug("OK"); + + EventBTSocketNotificationPtr event(new EventBTSocketNotification()); + event->setConnectionState(EventBTSocketNotification::SOCKETERROR); + + if (result == BT_ERROR_NONE) + { + if (connection_state == BT_SOCKET_DISCONNECTED) + { + event->setConnectionState(EventBTSocketNotification::DISCONNECTED); + } + } + + event->setSocketData(m_socketData); + m_EventBTSocketNotificationEmitterPtr->emit(event); + +} +void BluetoothSocketManager::setSocketData(BluetoothSocketData socketData) +{ + m_socketData = socketData; +} + + +int BluetoothSocketManager::setSocketNotifier(EventBTSocketNotificationEmitterPtr emitter) +{ + if (bt_socket_set_data_received_cb(capi_callback_bt_data_received, this) != BT_ERROR_NONE || + bt_socket_set_connection_state_changed_cb(capi_callback_bt_connection_state_changed, this) != BT_ERROR_NONE) + { + LogDebug("callback set error"); + return BT_ERROR_NOT_INITIALIZED; + } + + m_EventBTSocketNotificationEmitterPtr = emitter; + + return BT_ERROR_NONE; + +} +int BluetoothSocketManager::writeData(const char *data, const unsigned int length) +{ + LogDebug(length); + + if (m_socketData.connectedSocket < 0) + { + return BT_ERROR_NOT_INITIALIZED; + } + + + if (data == NULL || length == 0) + { + return BT_ERROR_INVALID_PARAMETER; + } + + + return bt_socket_send_data(m_socketData.connectedSocket, data, length); +} + +EventBTReadDataType BluetoothSocketManager::readData() +{ + DPL::Mutex::ScopedLock lock(&m_mtx); + + return m_readData; +} + + +int BluetoothSocketManager::close() +{ + DPL::Mutex::ScopedLock lock(&m_mtx); + int ret = 0; + + + if (m_socketData.isServer == true) + { + ret = bt_socket_destroy_rfcomm(m_socketData.registeredSocket); + } + else + { + ret = bt_socket_disconnect_rfcomm(m_socketData.connectedSocket); + } + + return ret; +} + +std::string BluetoothSocketManager::getUUID() +{ + return m_socketData.uuid; +} +unsigned int BluetoothSocketManager::getProtocol() +{ + return m_socketData.protocol; +} +unsigned int BluetoothSocketManager::getState() +{ + return m_socketData.state; +} +BluetoothDeviceData BluetoothSocketManager::getPeer() +{ + return m_socketData.peerDevice; +} +} +} +} diff --git a/src/platform/Tizen/Bluetooth/BluetoothSocketManager.h b/src/platform/Tizen/Bluetooth/BluetoothSocketManager.h new file mode 100644 index 0000000..343a623 --- /dev/null +++ b/src/platform/Tizen/Bluetooth/BluetoothSocketManager.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_PLATFROM_BLUETOOTH_SOCKET_MANAGER_H_ +#define TIZENAPIS_PLATFROM_BLUETOOTH_SOCKET_MANAGER_H_ + +#include +#include +#include +#include +#include +#include +#include + +using namespace TizenApis::Api; +using namespace TizenApis::Api::Bluetooth; + +namespace TizenApis { +namespace Platform { +namespace Bluetooth { + + +class BluetoothSocketManager : public Api::Bluetooth::IBluetoothSocketManager +{ + friend class TizenApis::Api::Bluetooth::BluetoothFactory; +public: + virtual ~BluetoothSocketManager(); + virtual std::string getUUID(); + virtual unsigned int getProtocol(); + virtual unsigned int getState(); + virtual BluetoothDeviceData getPeer(); + virtual int setSocketNotifier(EventBTSocketNotificationEmitterPtr emitter); + virtual int writeData(const char *data, const unsigned int length); + virtual EventBTReadDataType readData(); + virtual int close(); + virtual void setSocketData(BluetoothSocketData socketData); + virtual void setReadData(EventBTReadDataType readData); + void setDataReceivedEmit(bt_socket_received_data_s *data); + void connectionStateChangedEmit(int result, bt_socket_connection_state_e connection_state, + bt_socket_connection_s *connection); +private: + EventBTReadDataType m_readData; + DPL::Mutex m_mtx; + BluetoothSocketData m_socketData; + EventBTSocketNotificationEmitterPtr m_EventBTSocketNotificationEmitterPtr; +protected: + BluetoothSocketManager(); + +}; + +} +} +} + +#endif /* WRTPLUGINS_API_BluetoothSocketManager_H_ */ + diff --git a/src/platform/Tizen/Bluetooth/config.cmake b/src/platform/Tizen/Bluetooth/config.cmake new file mode 100755 index 0000000..30ed4b4 --- /dev/null +++ b/src/platform/Tizen/Bluetooth/config.cmake @@ -0,0 +1,20 @@ +get_current_path() + +pkg_search_module(capi-network-bluetooth REQUIRED capi-network-bluetooth) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_BLUETOOTH + ${capi-network-bluetooth_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_BLUETOOTH + ${capi-network-bluetooth_LIBRARIES} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_BLUETOOTH + ${CURRENT_PATH}/BluetoothAdapterManager.cpp + ${CURRENT_PATH}/BluetoothDeviceManager.cpp + ${CURRENT_PATH}/BluetoothSocketManager.cpp + PARENT_SCOPE +) diff --git a/src/platform/Tizen/Calendar/Calendar.cpp b/src/platform/Tizen/Calendar/Calendar.cpp new file mode 100755 index 0000000..6f16ae1 --- /dev/null +++ b/src/platform/Tizen/Calendar/Calendar.cpp @@ -0,0 +1,855 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include "Calendar.h" +#include "CalendarManager.h" +#include "CalendarQuery.h" +#include "CalendarFilter.h" +#include "API/Calendar/OnAddEventsChanged.h" +#include "API/Calendar/OnUpdateEventsChanged.h" +#include "API/Calendar/OnDeleteEventsChanged.h" +#include "API/Calendar/OnEventsChanged.h" +#include "API/Calendar/IEventWatchChanges.h" +#include "API/Calendar/IEventClearWatch.h" +#include "API/Calendar/EventId.h" +#include +#include +#include + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { +namespace Platform { +namespace Calendar { + +Calendar::Calendar() +{ + LogDebug("entered"); +} + +Calendar::~Calendar() +{ + LogDebug("entered"); +} + +void Calendar::OnRequestReceived(const IEventAddEventPtr &event) +{ + LogDebug("entered"); + Try + { + if (!event->getEvent()) { + ThrowMsg(NullPointerException, "event parameter is NULL"); + } + if (event->getEvent()->getIdIsSet()) { + LogWarning("adding event that is already added"); + event->getEvent()->resetId(); + } + DPL::ScopedPtr eventWrapper(new EventWrapper( + event->getEvent(), getType())); + event->getEvent()->setCalendarType(getType()); + eventWrapper->convertAbstractEventToPlatformEvent(); + if (event->checkCancelled()) { + event->setCancelAllowed(true); + event->setResult(true); + return; + } + eventWrapper->saveEvent(); + event->setResult(true); + } + catch (const Exception &ex) + { + LogError("Error during adding event" << ex.DumpToString()); + event->setResult(false); + } + event->setCancelAllowed(false); +} + +void Calendar::OnRequestReceived(const IEventAddEventsPtr &events) +{ + LogDebug("entered"); + Try + { + if (events->getEvents()->empty()) { + ThrowMsg(NullPointerException, "event vector parameter is empty"); + } + + // Save the vector of events iteratively + bool failedAdding = false; + for(unsigned int i=0; igetEvents()->size(); i++) + { + if (events->getEvents()->at(i)->getIdIsSet()) { + LogWarning("adding event that is already added: index " << i); + events->getEvents()->at(i)->resetId(); + } + DPL::ScopedPtr eventWrapper(new EventWrapper(events->getEvents()->at(i), getType())); + events->getEvents()->at(i)->setCalendarType(getType()); + eventWrapper->convertAbstractEventToPlatformEvent(); + if (events->checkCancelled()) { + events->setCancelAllowed(true); + events->setResult(true); + return; + } + + try { + eventWrapper->saveEvent(); + } catch (const Exception &saveException) { + LogInfo("Error during saving an event " << saveException.DumpToString()); + failedAdding = true; + } + //getAddEmitter()->emit(eventPtr); + } + + if( false==failedAdding ) { + events->setResult(true); + } else { + events->setResult(false); + } + } + catch (const Exception &ex) + { + LogError("Error during adding events" << ex.DumpToString()); + events->setResult(false); + } + events->setCancelAllowed(false); +} + +void Calendar::OnRequestReceived(const IEventUpdateEventPtr &event) +{ + LogDebug("entered"); + Try + { + if (!event->getEvent()) { + ThrowMsg(NullPointerException, "event parameter is NULL"); + } + if (!event->getEvent()->getIdIsSet()) { + ThrowMsg( + InvalidArgumentException, + "Cannot update non-existing event. Event needs adding or ID is wrong"); + } + DPL::ScopedPtr eventWrapper(new EventWrapper(event->getEvent(), getType())); + event->getEvent()->setCalendarType(getType()); + eventWrapper->convertAbstractEventToPlatformEvent(); + if (event->checkCancelled()) { + event->setCancelAllowed(true); + event->setResult(true); + return; + } + + if ( event->getUpdateAllInstances() || NULL==event->getEvent()->getRecurrenceRule()) + { + eventWrapper->saveEvent(); + } + else + { + LogDebug("Update the exception record"); + DPL::ScopedPtr eventWrapperChild(new EventWrapper(event->getEvent(), getType())); + eventWrapperChild->convertAbstractEventToPlatformEvent(); + + if ( CAL_SUCCESS!=calendar_svc_struct_set_int(eventWrapperChild->getPlatformEvent(), + CAL_VALUE_INT_ORIGINAL_EVENT_ID, event->getEvent()->getId()) ) { + ThrowMsg(PlatformException, "cannot save exception event"); + } + if (CAL_SUCCESS!=calendar_svc_struct_set_int(eventWrapperChild->getPlatformEvent(), + CAL_VALUE_INT_REPEAT_TERM,0) ) { + ThrowMsg(PlatformException, "cannot save exception event"); + } + int childId = calendar_svc_insert(eventWrapperChild->getPlatformEvent()); + if ( childId<0 ) { + ThrowMsg(PlatformException, "cannot save exception event"); + } + + GList* list = NULL; + cal_value *value = calendar_svc_value_new(CAL_VALUE_LST_EXCEPTION_DATE); + if (CAL_SUCCESS!=calendar_svc_value_set_time(value, CAL_VALUE_GMT_EXCEPTION_DATE_TIME, CAL_TZ_FLAG_GMT, event->getEvent()->getStartTime()) ) { + ThrowMsg(PlatformException, "cannot save the exception parent event"); + } + if (CAL_SUCCESS!=calendar_svc_value_set_int(value, CAL_VALUE_INT_EXCEPTION_DATE_ID, childId)) { + ThrowMsg(PlatformException, "cannot save the exception parent event"); + } + eventWrapper->loadEvent(event->getEvent()->getId()); + calendar_svc_struct_get_list(eventWrapper->getPlatformEvent(), CAL_VALUE_LST_EXCEPTION_DATE, &list); + list = g_list_append(list, value); + if (CAL_SUCCESS!=calendar_svc_struct_store_list(eventWrapper->getPlatformEvent(), CAL_VALUE_LST_EXCEPTION_DATE, list)) { + ThrowMsg(PlatformException, "cannot save the exception parent event"); + } + calendar_svc_update(eventWrapper->getPlatformEvent()); + + event->getEvent()->setIsDetached(true); + } + + event->setResult(true); + } + catch (const Exception &ex) + { + LogError("Error during updating event " << ex.DumpToString()); + event->setResult(false); + } + event->setCancelAllowed(false); +} + +void Calendar::OnRequestReceived(const IEventUpdateEventsPtr &events) +{ + LogDebug("entered"); + Try + { + if (events->getEvents()->empty()) { + ThrowMsg(NullPointerException, "event vector parameter is empty"); + } + + // Update the vector of events iteratively + bool failedUpdating = false; + for(unsigned int i=0; igetEvents()->size(); i++) + { + CalendarEventPtr thisEvent = events->getEvents()->at(i); + if (!thisEvent->getIdIsSet()) { + ThrowMsg(InvalidArgumentException, + "Cannot update non-existing event. Event needs adding or ID is wrong"); + } + DPL::ScopedPtr eventWrapper(new EventWrapper(thisEvent, getType())); + events->getEvents()->at(i)->setCalendarType(getType()); + eventWrapper->convertAbstractEventToPlatformEvent(); + if (events->checkCancelled()) { + events->setCancelAllowed(true); + events->setResult(true); + return; + } + + try { + if (events->getUpdateAllInstances() || NULL==thisEvent->getRecurrenceRule()) + { + eventWrapper->saveEvent(); + } + else + { + LogDebug("Update the exception record"); + DPL::ScopedPtr eventWrapperChild(new EventWrapper(thisEvent, getType())); + eventWrapperChild->convertAbstractEventToPlatformEvent(); + + if ( CAL_SUCCESS!=calendar_svc_struct_set_int(eventWrapperChild->getPlatformEvent(), + CAL_VALUE_INT_ORIGINAL_EVENT_ID, thisEvent->getId()) ) { + ThrowMsg(PlatformException, "cannot save exception event"); + } + if (CAL_SUCCESS!=calendar_svc_struct_set_int(eventWrapperChild->getPlatformEvent(), + CAL_VALUE_INT_REPEAT_TERM,0) ) { + ThrowMsg(PlatformException, "cannot save exception event"); + } + int childId = calendar_svc_insert(eventWrapperChild->getPlatformEvent()); + if ( childId<0 ) { + ThrowMsg(PlatformException, "cannot save exception event"); + } + + GList* list = NULL; + cal_value *value = calendar_svc_value_new(CAL_VALUE_LST_EXCEPTION_DATE); + if (CAL_SUCCESS!=calendar_svc_value_set_time(value, CAL_VALUE_GMT_EXCEPTION_DATE_TIME, CAL_TZ_FLAG_GMT, thisEvent->getStartTime()) ) { + ThrowMsg(PlatformException, "cannot save the exception parent event"); + } + if (CAL_SUCCESS!=calendar_svc_value_set_int(value, CAL_VALUE_INT_EXCEPTION_DATE_ID, childId)) { + ThrowMsg(PlatformException, "cannot save the exception parent event"); + } + calendar_svc_struct_get_list(eventWrapper->getPlatformEvent(), CAL_VALUE_LST_EXCEPTION_DATE, &list); + list = g_list_append(list, value); + if (CAL_SUCCESS!=calendar_svc_struct_store_list(eventWrapper->getPlatformEvent(), CAL_VALUE_LST_EXCEPTION_DATE, list)) { + ThrowMsg(PlatformException, "cannot save the exception parent event"); + } + calendar_svc_update(eventWrapper->getPlatformEvent()); + + thisEvent->setIsDetached(true); + } + } catch (const Exception &updateException) { + LogInfo("Error during updating an event " << updateException.DumpToString()); + failedUpdating = true; + } + //getUpdateEmitter()->emit(eventPtr); + } + + if( false==failedUpdating ) { + events->setResult(true); + } else { + events->setResult(false); + } + } + catch (const Exception &ex) + { + LogError("Error during updating events " << ex.DumpToString()); + events->setResult(false); + } + events->setCancelAllowed(false); +} + +void Calendar::OnRequestReceived(const IEventDeleteEventPtr &event) +{ + LogDebug("entered"); + Try + { + if (!event->getEventId()) { + ThrowMsg(NullPointerException, "event Id parameter is NULL"); + } + + DPL::ScopedPtr eventWrapper(new EventWrapper(getType())); + event->getEventId()->setCalendarType(getType()); + std::istringstream stream(event->getEventId()->getUId()); + int id = -1; + stream>>id; + //eventWrapper->getAbstractEvent()->setId(id); + eventWrapper->loadEvent(id); + LogDebug("event->getEventId()->getRecurrenceId() : " << event->getEventId()->getRecurrenceId()); + eventWrapper->getAbstractEvent()->setRecurrenceId(event->getEventId()->getRecurrenceId()); + + if (event->checkCancelled()) { + event->setCancelAllowed(true); + event->setResult(true); + return; + } + + eventWrapper->deleteEvent(); + event->setResult(true); + } + catch (const NotFoundException &ex) + { + LogError("event doesn't exist"); + event->setResult(false); + event->setExceptionCode(ExceptionCodes::NotFoundException); + } + catch (const Exception &ex) + { + LogError("Error during deleting event " << ex.DumpToString()); + event->setResult(false); + } + event->setCancelAllowed(false); +} + +void Calendar::OnRequestReceived(const IEventDeleteEventsPtr &events) +{ + LogDebug("entered"); + Try + { + if (events->getEventIds()->empty()) { + ThrowMsg(NullPointerException, "event vector parameter is empty"); + } + + // Delete the vector of events iteratively considering the recurrenceId + bool failedDeleting = false; + for(unsigned int i=0; igetEventIds()->size(); i++) + { + DPL::ScopedPtr eventWrapper(new EventWrapper(getType())); + events->getEventIds()->at(i)->setCalendarType(getType()); + std::istringstream stream(events->getEventIds()->at(i)->getUId()); + int id; + stream>>id; + eventWrapper->getAbstractEvent()->setId(id); + eventWrapper->getAbstractEvent()->setRecurrenceId(events->getEventIds()->at(i)->getRecurrenceId()); + eventWrapper->convertAbstractEventToPlatformEvent(); + if (events->checkCancelled()) { + events->setCancelAllowed(true); + events->setResult(true); + return; + } + + try { + eventWrapper->deleteEvent(); + } catch (const NotFoundException &ex) { + LogInfo("Event not found during deleting an event."); + events->setExceptionCode(ExceptionCodes::NotFoundException); + failedDeleting = true; + } catch (const Exception &ex) { + LogInfo("Exception occurred during deleting an event."); + events->setExceptionCode(ExceptionCodes::PlatformException); + failedDeleting = true; + } + } + + if( false==failedDeleting ) { + events->setResult(true); + } + else { + events->setResult(false); + } + } + catch (const NotFoundException &ex) + { + LogError("event doesn't exist"); + events->setResult(false); + events->setExceptionCode(ExceptionCodes::NotFoundException); + } + catch (const Exception &ex) + { + LogError("Error during deleting event " << ex.DumpToString()); + events->setResult(false); + } + events->setCancelAllowed(false); +} + +void Calendar::OnRequestReceived(const IEventFindEventsPtr &event) +{ + LogDebug("entered"); + const EventFilterPtr filter = event->getFilter(); + cal_struct *platformEvent = NULL; + cal_iter *iter = NULL; + event->setResult(true); + bool isStartDateSet = false; + + try + { + // Tizen Generic filter + if ( event->getGenericFilterIsSet() ) + { + CalendarFilterPtr calendarFilter( new CalendarFilter() ); + std::string query ("SELECT rowid, * FROM schedule_table"); + + TizenApis::Api::Tizen::IFilterVisitorPtr filterTraversal = DPL::StaticPointerCast(calendarFilter); + + if (event->getGenericFilterIsSet()) { + TizenApis::Api::Tizen::FilterPtr genericFilter = event->getGenericFilter(); + genericFilter->travel(filterTraversal, 0); + LogDebug("Traverse string [" << calendarFilter->getResult() << "]"); + query.append(calendarFilter->getResult()); + query.append(" AND is_deleted = 0"); + } else { + query.append(" WHERE is_deleted = 0"); + } + + if (event->getSortModesIsSet()) { + query.append(calendarFilter->makeQuerySortMode(event->getSortModes())); + } + + LogDebug("Filter query [" << query << "]"); + + calendarFilter->executeQuery(query, event->getEvents()); + + LogDebug("Result counter [" << event->getEvents()->size() << "]"); + } + // Tizen filter + else + { + if (NULL==filter) + { + LogInfo("Filter is not set."); + const char *dataType; + if(getType() == CalendarEvent::TASK_TYPE) { + dataType = CAL_STRUCT_TODO; + } else { + dataType = CAL_STRUCT_SCHEDULE; + } + + if (CAL_SUCCESS != calendar_svc_get_all(0, 0, dataType, &iter)) { + ThrowMsg(PlatformException, "Can't get all records"); + } + + } + else + // Use the new calendar service search function with multiple type/value pairs. + { + int filterCount = 0; + const char *searchType[9]; + const void *searchValue[9]; + + if(filter->getIdIsSet()) { + // Platform supports integer type db index only. + std::istringstream istream(filter->getIdFilter()); + int id; + istream>>id; + searchType[filterCount] = CAL_VALUE_INT_INDEX; + searchValue[filterCount++] = (void*)(id); + } + if(filter->getSubjectIsSet()) { + searchType[filterCount] = CAL_VALUE_TXT_SUMMARY; + searchValue[filterCount++] = (void*)(filter->getSubjectFilter().c_str()); + } + if(filter->getDescriptionIsSet()) { + searchType[filterCount] = CAL_VALUE_TXT_DESCRIPTION; + searchValue[filterCount++] = (void*)(filter->getDescriptionFilter().c_str()); + } + if(filter->getLocationIsSet()) { + searchType[filterCount] = CAL_VALUE_TXT_LOCATION; + searchValue[filterCount++] = (void*)(filter->getLocationFilter().c_str()); + } + if(filter->getCategoryIsSet()) { + searchType[filterCount] = CAL_VALUE_TXT_MEETING_CATEGORY_DETAIL_NAME; + searchValue[filterCount++] = (void*)(filter->getCategoryFilter().c_str()); + } + if(filter->getStatusIsSet()) { + std::stringstream ss; + std::string status; + for( unsigned int i=0; igetStatusFilter().size(); i++ ) { + cal_status_type_t statusValue = CAL_STATUS_CONFIRM; + switch(filter->getStatusFilter().at(i)) { + case CalendarEvent::TENTATIVE_STATUS: + statusValue = CAL_STATUS_TENTATIVE; + break; + case CalendarEvent::CANCELLED_STATUS: + statusValue = CAL_STATUS_DENIED; + break; + case CalendarEvent::CONFIRMED_STATUS: + default: + statusValue = CAL_STATUS_CONFIRM; + break; + } + ss<getStartTimeMinIsSet()) { + searchType[filterCount] = CAL_VALUE_GMT_START_DATE_TIME; + searchValue[filterCount++] = (void*)(filter->getStartTimeMinFilter()); + isStartDateSet = true; + } + if(filter->getStartTimeMaxIsSet()) { + searchType[filterCount] = CAL_VALUE_GMT_END_DATE_TIME; + searchValue[filterCount++] = (void*)(filter->getStartTimeMaxFilter()); + isStartDateSet = true; + } + LogInfo("Filter is set: "<tryCancelled(); + + platformEvent = NULL; + if (CAL_SUCCESS != + calendar_svc_iter_get_info(iter, &platformEvent)) { + ThrowMsg(PlatformException, "Can't get event info."); + } + + // platformEvent is freed when the wrapper destructor is called. + DPL::ScopedPtr eventWrapper(new EventWrapper(platformEvent, getType())); + + eventWrapper->convertPlatformEventToAbstractEvent()->setCalendarType(getType()); + event->addEvent(eventWrapper->getAbstractEvent()); + } + + // Process the recurring event cases here. + if ( isStartDateSet ) { + LogInfo("Process the recurring evets"); + if(CAL_SUCCESS != + calendar_svc_find_recurring_event_list(0, &iter)) { + ThrowMsg(PlatformException, "Can't find recurring event list."); + } + + time_t startTime, endTime, nextStartTime, nextEndTime; + if (filter->getStartTimeMinIsSet()) { + startTime = filter->getStartTimeMinFilter(); + } else { + startTime = 0; + } + if (filter->getStartTimeMaxIsSet()) { + endTime = filter->getStartTimeMaxFilter(); + } else { + endTime = INT_MAX; // about 60 years in 4 bytes system. + } + + while (CAL_SUCCESS == calendar_svc_iter_next(iter)) { + event->tryCancelled(); + + nextStartTime = 0; // It's important to reset this before calling calendar_svc_util_next_valid_event. + nextEndTime = 0; + platformEvent = NULL; + if (CAL_SUCCESS != + calendar_svc_iter_get_info(iter, &platformEvent)) { + ThrowMsg(PlatformException, "Can't get event info."); + } + + if ( CAL_SUCCESS == + calendar_svc_util_next_valid_event(platformEvent, startTime, endTime, &nextStartTime, &nextEndTime) ) { + bool isDuplicated = false; + for( unsigned int i=0; igetEvents()->size(); i++ ) { + if (calendar_svc_struct_get_int(platformEvent, CAL_VALUE_INT_INDEX)==event->getEvents()->at(i)->getId()) + isDuplicated = true; + } + if (!isDuplicated) { + LogInfo("Found a recurring event inbetween the start time period."); + DPL::ScopedPtr eventWrapper(new EventWrapper(platformEvent, getType())); + eventWrapper->convertPlatformEventToAbstractEvent()->setCalendarType(getType()); + event->addEvent(eventWrapper->getAbstractEvent()); + } + } + } + } + } + } + catch (const NotFoundException &ex) + { + event->setResult(false); + event->setExceptionCode(ExceptionCodes::NotFoundException); + } + catch (const Exception &ex) + { + LogError("Exception: " << ex.DumpToString()); + event->setResult(false); + } + + calendar_svc_iter_remove(&iter); + event->setCancelAllowed(true); +} + +void Calendar::OnRequestReceived(const IEventCreateEventPtr &event) +{ + LogDebug("entered"); + Try + { + event->setEvent(CalendarEventPtr(new CalendarEvent())); + event->getEvent()->setCalendarType(getType()); + event->setResult(event->getEvent().Get() != NULL); + } + catch (const Exception &ex) + { + LogError("Error during creating an event " << ex.DumpToString()); + event->setResult(false); + } +} + +void Calendar::OnRequestReceived(const IEventCreateEventFromStringPtr &event) +{ + LogDebug("entered"); + Try + { + if (event->checkCancelled()) { + event->setCancelAllowed(true); + event->setResult(true); + return; + } + + DPL::ScopedPtr eventWrapper(new EventWrapper(getType())); + eventWrapper->createEventFromString(event->getEventString()); + event->setEvent(eventWrapper->convertPlatformEventToAbstractEvent()); + event->getEvent()->setCalendarType(getType()); + event->setResult(true); + } + catch (const Exception &ex) + { + LogError("Error during creating event from string" << ex.DumpToString()); + LogInfo("eventString: " + event->getEventString()); + event->setResult(false); + } + event->setCancelAllowed(false); +} + +void Calendar::OnRequestReceived(const IEventExportEventToStringPtr &event) +{ + LogDebug("entered"); + Try + { + if (!event->getEvent()) { + ThrowMsg(NullPointerException, "event parameter is NULL"); + } + + if (event->checkCancelled()) { + event->setCancelAllowed(true); + event->setResult(true); + return; + } + + DPL::ScopedPtr eventWrapper(new EventWrapper(event->getEvent(), getType())); + event->getEvent()->setCalendarType(getType()); + eventWrapper->convertAbstractEventToPlatformEvent(); + event->setEventString(eventWrapper->exportEventToString()); + event->setResult(true); + } + catch (const Exception &ex) + { + LogError("Error during creating string from event" << ex.DumpToString()); + event->setResult(false); + } + event->setCancelAllowed(false); +} + +static void eventChangedCb(void *user_data) +{ + LogDebug("entered"); + + OnEventsChangedPtr eventPtr(new OnEventsChanged()); + try + { + Calendar *thisCalendar = (Calendar*) user_data; + + // Determine the status of event change. + cal_iter *iter = NULL; + cal_struct *platformEvent = NULL; + int index; + int syncStatus; + + if( CAL_SUCCESS != calendar_svc_get_updated_event_list(thisCalendar->getAccountId(), + thisCalendar->getLastChangeFetchTime(), + &iter) ) { + ThrowMsg(PlatformException, "Can't get the updated event list."); + } + while( CAL_SUCCESS == calendar_svc_iter_next(iter) ) + { + if ( CAL_SUCCESS != calendar_svc_iter_get_info(iter, &platformEvent) ) { + ThrowMsg(PlatformException, "Can't get the calendar info."); + } + + index = calendar_svc_struct_get_int(platformEvent, CAL_VALUE_INT_INDEX); + syncStatus = calendar_svc_struct_get_int(platformEvent, CAL_VALUE_INT_SYNC_STATUS); + LogDebug("index "<setStatus(OnEventsChanged::ON_ADD); + } else if ( CAL_SYNC_STATUS_UPDATED==syncStatus ) { + eventPtr->setStatus(OnEventsChanged::ON_UPDATE); + } else if ( CAL_SYNC_STATUS_DELETED==syncStatus ) { + eventPtr->setStatus(OnEventsChanged::ON_DELETE); + } else { + if( platformEvent ) { + calendar_svc_struct_free(&platformEvent); + } + calendar_svc_iter_remove(&iter); + ThrowMsg(PlatformException, "Wrong syncStatus."); + } + + DPL::ScopedPtr eventWrapper(new EventWrapper(thisCalendar->getType())); + eventWrapper->loadEvent(index); + eventPtr->addEvent(eventWrapper->getAbstractEvent()); + + if ( CAL_SUCCESS != calendar_svc_struct_free(&platformEvent) ) { + ThrowMsg(PlatformException, "Can't free the platform event struct."); + } + } + + if ( CAL_SUCCESS != calendar_svc_iter_remove(&iter) ) { + ThrowMsg(PlatformException, "Can't remove the iter."); + } + + std::time_t localTime = time(NULL); + thisCalendar->setLastChangeFetchTime(localTime); + LogInfo("Last change fetch time: "<getLastChangeFetchTime()); + + eventPtr->setResult(true); + + if( eventPtr->getEventList()->size() > 0 ) { + thisCalendar->m_changeEmitters.emit(eventPtr); + } else { + LogInfo("No actual changes. Skip signal emission."); + } + } + catch (const Exception &ex) + { + LogError("Error while emitting the change noti" << ex.DumpToString()); + } +} + +void Calendar::OnRequestReceived(const IEventWatchChangesPtr &event) +{ + LogDebug("entered"); + Try + { + // Subscribe the watch to the platform just once. + if( m_changeEmitters.size()==0 ) + { + if( CAL_SUCCESS!=calendar_svc_subscribe_change(eventChangedCb, this) ) { + ThrowMsg(PlatformException, "Can't subscribe the db change noti."); + event->setResult(false); + return; + } else { + // Save the last change fetch time to start watching. + std::time_t localTime = time(NULL); + setLastChangeFetchTime(localTime); + LogInfo("Last change fetch time: "<getEmitter()); + event->setWatchId(event->getEmitter()->getId()); + event->setResult(true); + } + catch (const Exception &ex) + { + LogError("Error during creating a watch " << ex.DumpToString()); + event->setResult(false); + } +} + +void Calendar::OnRequestReceived(const IEventClearWatchPtr &event) +{ + LogDebug("entered"); + Try + { + m_changeEmitters.detach(event->getWatchId()); + + if( m_changeEmitters.size()==0 ) { + if( CAL_SUCCESS!=calendar_svc_unsubscribe_change(eventChangedCb) ) { + ThrowMsg(PlatformException, "Can't unsubscribe the db change noti."); + event->setResult(false); + return; + } else { + LogDebug("Platform watch cleared successfully."); + } + } + event->setResult(true); + } + catch (const Exception &ex) + { + LogError("Error during clearing the watch " << ex.DumpToString()); + event->setResult(false); + } +} + +void Calendar::OnRequestReceived(const IEventExpandEventRecurrencePtr &event) +{ + LogDebug("entered"); + const CalendarEventPtr calEvent = event->getEvent(); + const time_t startDate = event->getStartDate(); + const time_t endDate = event->getEndDate(); + event->setResult(true); + + try { + if ( 0 >= calEvent->getRecurrenceRule()->getFrequency()) + { + ThrowMsg(PlatformException, "This is not a recurring event."); + } + + std::time_t nextStartTime = 0; + std::time_t nextEndTime = 0; + + DPL::ScopedPtr eventWrapper(new EventWrapper(event->getEvent(), getType())); + eventWrapper->convertAbstractEventToPlatformEvent(); + + event->tryCancelled(); + + while ( CAL_SUCCESS == + calendar_svc_util_next_valid_event(eventWrapper->getPlatformEvent(), startDate, endDate, &nextStartTime, &nextEndTime) ) { + LogInfo("Found a next vaild event: "< recurringEventWrapper(new EventWrapper(getType())); + recurringEventWrapper->loadEvent(calEvent->getId()); + recurringEventWrapper->getAbstractEvent()->setRecurrenceId(nextStartTime); + event->addExpandedEvent(recurringEventWrapper->getAbstractEvent()); + } + + LogInfo("Length of expanded events: "<getExpandedEventList()->size()); + } + catch (const Exception &ex) + { + LogError("Exception: " << ex.DumpToString()); + event->setResult(false); + } + + event->setCancelAllowed(true); +} + +} +} +} diff --git a/src/platform/Tizen/Calendar/Calendar.h b/src/platform/Tizen/Calendar/Calendar.h new file mode 100755 index 0000000..f338da1 --- /dev/null +++ b/src/platform/Tizen/Calendar/Calendar.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _CALENDAR_H_ +#define _CALENDAR_H_ + +#include +#include "API/Calendar/ICalendar.h" +#include "EventWrapper.h" + +using namespace TizenApis::Api::Calendar; + +namespace TizenApis { +namespace Platform { +namespace Calendar { + +class Calendar : public ICalendar +{ + public: + Calendar(); + virtual ~Calendar(); + protected: + virtual void OnRequestReceived(const IEventAddEventPtr &event); + virtual void OnRequestReceived(const IEventAddEventsPtr &events); + virtual void OnRequestReceived(const IEventDeleteEventPtr &event); + virtual void OnRequestReceived(const IEventDeleteEventsPtr &events); + virtual void OnRequestReceived(const IEventUpdateEventPtr &event); + virtual void OnRequestReceived(const IEventUpdateEventsPtr &events); + virtual void OnRequestReceived(const IEventFindEventsPtr &event); + virtual void OnRequestReceived(const IEventCreateEventPtr &event); + virtual void OnRequestReceived(const IEventCreateEventFromStringPtr &event); + virtual void OnRequestReceived(const IEventExportEventToStringPtr &event); + virtual void OnRequestReceived(const IEventWatchChangesPtr &event); + virtual void OnRequestReceived(const IEventClearWatchPtr &event); + virtual void OnRequestReceived(const IEventExpandEventRecurrencePtr &event); +}; + +} +} +} + +#endif /* _CALENDAR_H_ */ diff --git a/src/platform/Tizen/Calendar/CalendarFilter.cpp b/src/platform/Tizen/Calendar/CalendarFilter.cpp new file mode 100755 index 0000000..9e9a076 --- /dev/null +++ b/src/platform/Tizen/Calendar/CalendarFilter.cpp @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include "CalendarFilter.h" +#include "CalendarQuery.h" +#include + +using namespace TizenApis::Api::Calendar; + +namespace TizenApis { +namespace Platform { +namespace Calendar { + +CalendarFilter::CalendarFilter() : m_query("") +{ + LogDebug("entered"); + init(); +} + +CalendarFilter::~CalendarFilter() +{ +} + +void CalendarFilter::visitPreComposite(TizenApis::Api::Tizen::FilterType& type, int depth) +{ + LogDebug("entered"); + m_query = m_query + " ("; +} + +void CalendarFilter::visitInComposite(TizenApis::Api::Tizen::FilterType& type, int depth) +{ + LogDebug("entered"); + if(type == TizenApis::Api::Tizen::UNION_FILTER) + m_query = m_query + " OR "; + else if(type == TizenApis::Api::Tizen::INTERSECTION_FILTER) + m_query = m_query + " AND "; +} + +void CalendarFilter::visitPostComposite(TizenApis::Api::Tizen::FilterType& type, int depth) +{ + LogDebug("entered"); + m_query = m_query + " )"; +} + +void CalendarFilter::visitAttribute(std::string& attrName, TizenApis::Api::Tizen::AnyArrayPtr& matchValues, std::string& matchFlag, bool caseSensitive, int depth) +{ + LogDebug("attrName [" << attrName << "] value length[" << matchValues->size() << "] matchFlag [" << matchFlag << "] caseSensitive [" <" + initialValue->toString() + " AND " + attrName + "<" + endValue->toString()+ " "; + m_query = m_query + str; +} + +void CalendarFilter::visitID(TizenApis::Api::Tizen::AnyArrayPtr &value, int depth) +{ + +} + +void CalendarFilter::init() +{ + LogDebug("entered"); + m_query.clear(); + m_query.append(" WHERE"); +} + +std::string CalendarFilter::convertAttribute(std::string &name, TizenApis::Api::Tizen::AnyArrayPtr& matchValues) +{ + std::string query(""); + + if (name.compare("id") == 0) { + query = " (" + name + "= " + matchValues->at(0)->toString() + ")"; + } else if (name.compare("summary") == 0) { + query = " (" + name + "= " + matchValues->at(0)->toString() + ")"; + } + + LogDebug("query-filter :[" << query << "]"); + return query; +} + +std::string CalendarFilter::getResult() const +{ + LogDebug("entered"); + return m_query; +} + +bool CalendarFilter::convertCalendar(calendar_query_s *query_log, CalendarEventListPtr calendarListPtr) +{ + LogDebug("entered"); + + if (query_log == NULL) + return false; + + CalendarEventPtr calendarEvent(new CalendarEvent()); + + // convert query results to the event struct. + + calendarEvent->setId(query_log->rowid); + calendarEvent->setSubject(query_log->summary); + + calendarListPtr->push_back(calendarEvent); + + return true; +} + +bool CalendarFilter::executeQuery(std::string &query, CalendarEventListPtr calendarListPtr) +{ + LogDebug("entered"); + + calendar_query_s query_data; + + stmt hstmt = NULL; + int ret = 0; + + hstmt = _query_prepare((char *)(query.c_str())); + + do { + ret = _query_step(hstmt); + LogDebug("Query result : [" << ret << "]"); + if (ret == SQLITE_ROW) { + query_data.rowid = _query_column_int(hstmt, 0); + query_data.summary = _query_column_text(hstmt, 1); + + convertCalendar(&query_data, calendarListPtr); + } else if (ret == SQLITE_DONE) { + LogDebug("Query done [" << ret << "]"); + break; + } else { //if (ret == SQLITE_DONE || ret == SQLITE_IOERR || ret == SQLITE_BUSY || ret == SQLITE_ERROR || ret == SQLITE_MISUSE) + LogDebug("Query error [" << ret << "]"); + break; + } + } while (1); + + _query_finalize(hstmt); + return true; +} + +std::string CalendarFilter::makeQuerySortMode(TizenApis::Api::Tizen::SortModeArrayPtr attr) +{ + LogDebug("entered"); + + std::string query(""); + std::string attriName; + int cnt = 0; + TizenApis::Api::Tizen::SortModeArray::iterator it = attr->begin(); + + for (;it!=attr->end(); ++it) { + attriName = (*it)->getAttributeName(); + if (attriName.compare("") != 0) { + if (cnt == 0) { + query.append(" ORDER BY "); + } else { + query.append(", "); + } + query.append(attriName); + + if ((*it)->getOrder() == TizenApis::Api::Tizen::ASCENDING_SORT_ORDER) { + query.append(" ASC"); + } else { + query.append(" DESC"); + } + cnt++; + } + } + + return query; +} + +} +} +} diff --git a/src/platform/Tizen/Calendar/CalendarFilter.h b/src/platform/Tizen/Calendar/CalendarFilter.h new file mode 100755 index 0000000..4b22f1b --- /dev/null +++ b/src/platform/Tizen/Calendar/CalendarFilter.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _CALENDAR_FILTER_H_ +#define _CALENDAR_FILTER_H_ + +#include +#include +#include +#include +#include "API/Calendar/CalendarEvent.h" +#include "CalendarQuery.h" + +using namespace TizenApis::Api::Calendar; + +namespace TizenApis { +namespace Platform { +namespace Calendar { + +class CalendarFilter: public TizenApis::Api::Tizen::IFilterVisitor +{ +private: + std::string m_query; + +public: + CalendarFilter(); + virtual ~CalendarFilter(); + + virtual void visitPreComposite(TizenApis::Api::Tizen::FilterType& type, int depth); + + virtual void visitInComposite(TizenApis::Api::Tizen::FilterType& type, int depth); + + virtual void visitPostComposite(TizenApis::Api::Tizen::FilterType& type, int depth); + + virtual void visitAttribute(std::string& attrName, + TizenApis::Api::Tizen::AnyArrayPtr& matchValues, + std::string& matchFlag, + bool caseSensitive, + int depth); + + virtual void visitAttributeRange(std::string& attrName, + TizenApis::Api::Tizen::AnyPtr& initialValue, + TizenApis::Api::Tizen::AnyPtr& endValue, + int depth); + + virtual void visitID(TizenApis::Api::Tizen::AnyArrayPtr &value, int depth); + + void init(); + std::string getResult() const; + std::string convertAttribute(std::string &name, TizenApis::Api::Tizen::AnyArrayPtr& matchValues); + + bool convertCalendar(calendar_query_s *query_log, CalendarEventListPtr calendarListPtr); + + bool executeQuery(std::string &query, CalendarEventListPtr calendarListPtr); + + std::string makeQuerySortMode(TizenApis::Api::Tizen::SortModeArrayPtr attr); + +}; + +typedef DPL::SharedPtr CalendarFilterPtr; + +} +} +} + +#endif /* _CALENDAR_FILTER_H_ */ diff --git a/src/platform/Tizen/Calendar/CalendarManager.cpp b/src/platform/Tizen/Calendar/CalendarManager.cpp new file mode 100755 index 0000000..d703fea --- /dev/null +++ b/src/platform/Tizen/Calendar/CalendarManager.cpp @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "CalendarManager.h" +#include +#include +#include +#include +#include +#include + +namespace { +const char* SERVICE_PROVIDER_NAME = "phone"; +} + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { +namespace Platform { +namespace Calendar { + +int CalendarManager::m_instanceCount = 0; + +CalendarManager::CalendarManager() +{ + LogDebug("entered"); + /* Platform doesn't support calendar manager. + * This implementation have to implement it on its own. + * One calendar have to be created and stored for further use. + */ + DPL::Mutex::ScopedLock mx(&m_constructorMutex); + if (m_instanceCount == 0) { + LogDebug("opening calendar DB"); + if (CAL_SUCCESS != calendar_svc_connect()) { + ThrowMsg(PlatformException, + "Calendar DB initialization failed"); + } + } + m_instanceCount++; +} + +CalendarManager::~CalendarManager() +{ + LogDebug("entered"); + DPL::Mutex::ScopedLock mx(&m_constructorMutex); + m_instanceCount--; + if (m_instanceCount == 0) { + LogDebug("closing calendar DB"); + if (CAL_SUCCESS != calendar_svc_close()) { + LogError("Calendar database not clearly closed."); + } + } +} + +const char *CalendarManager::getServiceProviderName() +{ + return SERVICE_PROVIDER_NAME; +} + +void CalendarManager::OnRequestReceived(const IEventGetCalendarsPtr &event) +{ + static std::vector calendars; + Try + { + if (calendars.empty()) { + cal_iter *iter = NULL; + if (CAL_SUCCESS != + calendar_svc_get_all(ALL_ACCOUNT_ID, 0, CAL_STRUCT_CALENDAR, + &iter)) { + event->setResult(false); + return; + } + cal_struct *calendar = NULL; + while (CAL_SUCCESS == calendar_svc_iter_next(iter)) { + if (event->checkCancelled()) { + break; + } + if (CAL_SUCCESS == + calendar_svc_iter_get_info(iter, &calendar)) { + const char* name = calendar_svc_struct_get_str( + calendar, + CAL_TABLE_TXT_NAME); + const char* id = calendar_svc_struct_get_str( + calendar, + CAL_TABLE_TXT_CALENDAR_ID); + const int accountId = calendar_svc_struct_get_int( + calendar, + CAL_TABLE_INT_ACCOUNT_ID); + if (name != NULL && id != NULL) { + LogDebug( + "Got calendar, id: " << id << ", name: " << name << + ", account id: " << accountId); + ICalendarPtr newCalendar(new Calendar()); + newCalendar->setName(name); + newCalendar->setId(id); + newCalendar->setAccountId(accountId); + newCalendar->setType(event->getType()); + calendars.push_back(newCalendar); + } else { + LogError("calendar contains invalid parameters"); + } + calendar_svc_struct_free(&calendar); + calendar = NULL; + } else { + LogError("cannot get calendar"); + } + } + calendar_svc_iter_remove(&iter); + } + + if (!event->checkCancelled()) { + std::vector::const_iterator it = calendars.begin(); + for (; it != calendars.end(); ++it) { + event->addCalendar(*it); + } + event->setResult(true); + } + } + Catch(Exception) + { + LogError("error occuered during obtaining data"); + event->setResult(false); + } + event->setCancelAllowed(true); +} + +void CalendarManager::OnRequestReceived(const IEventGetDefaultCalendarPtr &event) +{ + ICalendarPtr newCalendar(new Calendar()); + Try + { + cal_iter *iter = NULL; + if (CAL_SUCCESS != + calendar_svc_get_all(ALL_ACCOUNT_ID, DEFAULT_CALENDAR_ID, CAL_STRUCT_CALENDAR, + &iter)) { + event->setResult(false); + return; + } + cal_struct *calendar = NULL; + while (CAL_SUCCESS == calendar_svc_iter_next(iter)) { + if (event->checkCancelled()) { + break; + } + if (CAL_SUCCESS == + calendar_svc_iter_get_info(iter, &calendar)) { + const char* name = calendar_svc_struct_get_str( + calendar, + CAL_TABLE_TXT_NAME); + const char* id = calendar_svc_struct_get_str( + calendar, + CAL_TABLE_TXT_CALENDAR_ID); + const int accountId = calendar_svc_struct_get_int( + calendar, + CAL_TABLE_INT_ACCOUNT_ID); + if (name != NULL && id != NULL) { + LogDebug( + "Got default calendar, id: " << id << ", name: " << name << + ", account id: " << accountId); + newCalendar->setName(name); + newCalendar->setId(id); + newCalendar->setAccountId(accountId); + newCalendar->setType(event->getType()); + event->setCalendar(newCalendar); + break; + } else { + LogError("calendar contains invalid parameters"); + } + calendar_svc_struct_free(&calendar); + calendar = NULL; + } else { + LogError("cannot get calendar"); + } + } + calendar_svc_iter_remove(&iter); + + event->setResult(true); + } + Catch(Exception) + { + LogError("error occuered during obtaining data"); + event->setResult(false); + } + event->setCancelAllowed(true); +} + +} +} +} diff --git a/src/platform/Tizen/Calendar/CalendarManager.h b/src/platform/Tizen/Calendar/CalendarManager.h new file mode 100755 index 0000000..6c1f6da --- /dev/null +++ b/src/platform/Tizen/Calendar/CalendarManager.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _CALENDARMANAGER_H_ +#define _CALENDARMANAGER_H_ + +#include +#include +#include +#include +#include "Calendar.h" + +namespace TizenApis { +namespace Platform { +namespace Calendar { + +class CalendarManager : public Api::Calendar::ICalendarManager +{ + public: + CalendarManager(); + virtual ~CalendarManager(); + static const char* getServiceProviderName(); + protected: + virtual void OnRequestReceived(const IEventGetCalendarsPtr &event); + virtual void OnRequestReceived(const IEventGetDefaultCalendarPtr &event); + + private: + static int m_instanceCount; + DPL::Mutex m_constructorMutex; +}; + +} +} +} + +#endif /* _CALENDARMANAGER_H_ */ diff --git a/src/platform/Tizen/Calendar/CalendarQuery.c b/src/platform/Tizen/Calendar/CalendarQuery.c new file mode 100755 index 0000000..d6fda66 --- /dev/null +++ b/src/platform/Tizen/Calendar/CalendarQuery.c @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "CalendarQuery.h" +#include +#include + +sqlite3 *hDBCt; + +static int db_connnect_count = 0; + +query_error _db_init() +{ + int rc = 0; + query_error error_code = QUERY_SUCCESS; + + db_connnect_count++; + if(!hDBCt) + { + rc = db_util_open(CALENDAR_DB_PATH, &hDBCt, 0); + if(rc != SQLITE_OK) + error_code = QUERY_FAIL; + } + return error_code; +} + +query_error _db_finish() +{ + int rc = 0; + query_error error_code = QUERY_SUCCESS; + + db_connnect_count--; + if(db_connnect_count == 0) + { + rc = db_util_close(hDBCt); + if(rc != SQLITE_OK) + error_code = QUERY_FAIL; + else + hDBCt = NULL; + } + return error_code; +} + +query_error _exec_query(char* query) +{ + int rc = -1; + char* pszErrorMsg = NULL; + query_error error_code = QUERY_SUCCESS; + + rc = sqlite3_exec(hDBCt, query, NULL, NULL, &pszErrorMsg); + + if(SQLITE_OK != rc) + { + error_code = QUERY_FAIL; + } + + if(pszErrorMsg) + sqlite3_free(pszErrorMsg); + + return error_code; +} + +int _query_step(stmt pStmt) +{ + return sqlite3_step(pStmt); +} + +void _contact_query_finalize(stmt pStmt) +{ + int rc = -1; + + if(!pStmt) + return; + + rc = sqlite3_finalize(pStmt); + if(rc != SQLITE_OK) + { + } +} + +int _calendar_query_column_int(stmt pStmt, int pos) +{ + return (int)sqlite3_column_int(pStmt, pos); +} + +char* _calendar_query_column_text(stmt pStmt, int pos) +{ + return (char *)sqlite3_column_text(pStmt, pos); +} + +void _query_finalize(stmt pStmt) +{ + int rc = -1; + + if(!pStmt) + return; + + rc = sqlite3_finalize(pStmt); + if(rc != SQLITE_OK) + { + + } +} + +int _query_bind_double(stmt pStmt, int pos, double num) +{ + return sqlite3_bind_double(pStmt, pos, num); +} + +int _query_bind_int(stmt pStmt, int pos, int num) +{ + return sqlite3_bind_int(pStmt, pos, num); +} + +int _query_bind_text(stmt pStmt, int pos, char* str) +{ + int len = 0; + if(str != NULL) + { + len = strlen(str); + return sqlite3_bind_text(pStmt, pos, (const char*)str, len, SQLITE_STATIC); + } + return -1; +} + +void _query_stmt_reset(stmt stmt) +{ + sqlite3_reset(stmt); + sqlite3_clear_bindings(stmt); +} + +int _query_column_int(stmt pStmt, int pos) +{ + return sqlite3_column_int(pStmt, pos); +} + +double _query_column_double(stmt pStmt, int pos) +{ + return sqlite3_column_double(pStmt, pos); +} + +char* _query_column_text(stmt pStmt, int pos) +{ + return (char *)sqlite3_column_text(pStmt, pos); +} + +stmt _query_prepare(char *query) +{ + int rc = -1; + stmt pStmt = NULL; + + printf("\nquery : %s !!!!\n", query); + + rc = sqlite3_prepare_v2(hDBCt, query, strlen(query), &pStmt, NULL); + + if(SQLITE_OK != rc) + { + return NULL; + } + + return pStmt; +} + diff --git a/src/platform/Tizen/Calendar/CalendarQuery.h b/src/platform/Tizen/Calendar/CalendarQuery.h new file mode 100755 index 0000000..7c6453d --- /dev/null +++ b/src/platform/Tizen/Calendar/CalendarQuery.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _CALENDAR_QUERY_H_ +#define _CALENDAR_QUERY_H_ + +#include +//#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#define CALENDAR_DB_PATH "/opt/dbspace/.calendar-svc.db" + +typedef sqlite3_stmt* stmt; + +// Query results struct +typedef struct +{ + int rowid; /**< Calendar id in database */ + char* summary; +} calendar_query_s; + +typedef enum +{ + QUERY_GROUP_CASE = -16, + QUERY_NORMALIZATION_ERROR = -15, + QUERY_SET_LIMIT = -14, /**< For limit operation */ + QUERY_NO_NEXT_ROW = -13, /**< No Row*/ + QUERY_INSERT_FAIL = -12, + QUERY_ORDERING_FAIL = -11, + QUERY_STATEMENT_FAIL = -10, + QUERY_INVALID_ATTRIBUTE = -9, + QUERY_OVER_MAX_COUNT = -8, /**< memory allocation fail */ + QUERY_OVER_MAX_PROPERTY_CLASS = -7, /**< Invalid property */ + QUERY_NULL_PARAMETER = -6, /**< null input data */ + QUERY_NO_RECORD = -5, /**< No Record */ + QUERY_HANDLE_NONE, /**< No handle */ + QUERY_INVALID_TYPE, /**< invalid value type */ + QUERY_ALLOCATE_MEMORY_FAIL, /**< memory allocation fail */ + QUERY_FAIL = -1, /**< fail */ + QUERY_SUCCESS = 0, /**< no error */ +}query_error; + +query_error _db_init(); + +query_error _db_finish(); + +query_error _exec_query(char* query); + +int _query_step(stmt pStmt); + +void _calendar_query_finalize(stmt pStmt); + +int _calendar_query_column_int(stmt pStmt, int pos); + +char* _calendar_query_column_text(stmt pStmt, int pos); + +void _query_finalize(stmt pStmt); + +int _query_bind_int(stmt pStmt, int pos, int num); + +int _query_bind_double(stmt pStmt, int pos, double num); + +int _query_bind_text(stmt pStmt, int pos, char* str); + +void _query_stmt_reset(stmt stmt); + +int _query_column_int(stmt pStmt, int pos); + +double _query_column_double(stmt pStmt, int pos); + +char* _query_column_text(stmt pStmt, int pos); + +stmt _query_prepare(char *query); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif // _CALENDAR_QUERY_H_ + diff --git a/src/platform/Tizen/Calendar/EventWrapper.cpp b/src/platform/Tizen/Calendar/EventWrapper.cpp new file mode 100755 index 0000000..189d383 --- /dev/null +++ b/src/platform/Tizen/Calendar/EventWrapper.cpp @@ -0,0 +1,2121 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include "EventWrapper.h" +#include "Calendar.h" + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; + +namespace { +const char WEEKDAYS[] = "0111110"; +const int NEW_EVENT_ID = -1; +} + +namespace TizenApis { +namespace Platform { +namespace Calendar { + +EventWrapper::EventWrapper(Api::Calendar::CalendarEvent::CalendarType type) : + m_platformEvent(NULL), + m_abstractEvent(NULL), + m_calendarType(type) +{ + LogDebug("entered"); + m_abstractEvent = CalendarEventPtr(new CalendarEvent()); + if (!m_abstractEvent) { + ThrowMsg(UnknownException, "abstract object is not created"); + } +} + +EventWrapper::EventWrapper(const CalendarEventPtr &event, Api::Calendar::CalendarEvent::CalendarType type) : + m_platformEvent(NULL), + m_abstractEvent(event), + m_calendarType(type) +{ + LogDebug("entered"); +} + +EventWrapper::EventWrapper(cal_struct *event, Api::Calendar::CalendarEvent::CalendarType type) : + m_platformEvent(event), + m_abstractEvent(NULL), + m_calendarType(type) +{ + LogDebug("entered"); + m_abstractEvent = CalendarEventPtr(new CalendarEvent()); + if (!m_abstractEvent) { + ThrowMsg(UnknownException, "abstract object is not created"); + } +} + +EventWrapper::~EventWrapper() +{ + LogDebug("entered"); + freePlatformEvent(); +} + +int EventWrapper::getIDFromPlatformEvent() const +{ + LogDebug("Entered"); + if (m_platformEvent == NULL) { + ThrowMsg(NullPointerException, "m_platformEvent is not set"); + } + + return calendar_svc_struct_get_int(m_platformEvent, CAL_VALUE_INT_INDEX); +} + +void EventWrapper::saveEvent() +{ + LogDebug("entered"); + if (m_platformEvent == NULL) { + ThrowMsg(NullPointerException, "m_platformEvent is not set"); + } + + int eventID = getIDFromPlatformEvent(); + LogDebug("Before saving/update eventID: " << eventID); + + displayPlatformEvent(); + + //insert new record or update existing one + if (eventID < 0) { //insert new event + int returnValue = calendar_svc_insert(m_platformEvent); + if (CAL_SUCCESS > returnValue) { + LogError("Can't insert new event, error code: " << returnValue); + ThrowMsg(PlatformException, "Can't insert new event."); + } + m_abstractEvent->setId(returnValue); + + //save the uid here too. + std::stringstream ss; + ss<setUId(ss.str()); + LogInfo("New calendar event inserted with id "< errorCode) { + ThrowMsg(PlatformException, + "Can't get event with ID = " << id << ", error code: " << + errorCode); + } + // Consider that the event is not found if the last modified date is 0. + if ( 0==calendar_svc_struct_get_time( + m_platformEvent, + CAL_VALUE_GMT_LAST_MODIFIED_TIME, + CAL_TZ_FLAG_GMT) ) { + ThrowMsg(NotFoundException, "Can't get event with provided id."); + } + + convertPlatformEventToAbstractEvent(); + displayAbstractEvent(); +} + +void EventWrapper::deleteEvent() +{ + LogDebug("entered"); + if (m_platformEvent == NULL) { + ThrowMsg(NullPointerException, + "Failed to delete event in calendar (m_platformEvent==NULL)"); + } + + // If the recurrenceId is set, delete the instance of recurring event only. + int eventID = getIDFromPlatformEvent(); + std::time_t recurrenceId = m_abstractEvent->getRecurrenceId(); + LogDebug("eventID to delete: " << eventID << ", recurrenceId: " << recurrenceId); + if (eventID < 0) { + ThrowMsg( + InvalidArgumentException, + "Failed to delete event in calendar (event is not saved in calendar)"); + } + + cal_struct *event = NULL; + const char *dataType; + if(getType() == CalendarEvent::TASK_TYPE) { + dataType = CAL_STRUCT_TODO; + } else { + dataType = CAL_STRUCT_SCHEDULE; + } + + int error = calendar_svc_get(dataType, eventID, NULL, &event); + if (CAL_SUCCESS != error) { + if (event) { + calendar_svc_struct_free(&event); + } + ThrowMsg(PlatformException, + "Can't get calendar event. Error code "<< error); + } + // Consider that the event is not found if the last modified date is 0. + if ( 0==calendar_svc_struct_get_time( + event, + CAL_VALUE_GMT_LAST_MODIFIED_TIME, + CAL_TZ_FLAG_GMT) ) { + if (event) { + calendar_svc_struct_free(&event); + } + ThrowMsg(NotFoundException, "Can't get event with provided id."); + } + if (event) { + calendar_svc_struct_free(&event); + } + + if ( 0>=recurrenceId || + !(EventRecurrenceRule::DAILY_RECURRENCE <= m_abstractEvent->getRecurrenceRule()->getFrequency() && m_abstractEvent->getRecurrenceRule()->getFrequency() <= EventRecurrenceRule::MONTHLY_ON_DAY_RECURRENCE)) { + const char *dataType; + if(getType() == CalendarEvent::TASK_TYPE) { + dataType = CAL_STRUCT_TODO; + } else { + dataType = CAL_STRUCT_SCHEDULE; + } + error = calendar_svc_delete(dataType, eventID); + if (CAL_SUCCESS != error) { + ThrowMsg(PlatformException, + "Can't delete calendar event. Error code " << error); + } + m_abstractEvent->resetId(); + setIDToPlatformEvent(); + LogDebug("The event is deleted regardless of recurrence"); + } else { + GList* list = NULL; + cal_value *value = calendar_svc_value_new(CAL_VALUE_LST_EXCEPTION_DATE); + if (CAL_SUCCESS!=calendar_svc_value_set_time(value, CAL_VALUE_GMT_EXCEPTION_DATE_TIME, CAL_TZ_FLAG_GMT, recurrenceId) ) { + if (value) { + calendar_svc_value_free(&value); + } + ThrowMsg(PlatformException, "cannot save the exception date"); + } + calendar_svc_struct_get_list(m_platformEvent, CAL_VALUE_LST_EXCEPTION_DATE, &list); + list = g_list_append(list, value); + if (CAL_SUCCESS!=calendar_svc_struct_store_list(m_platformEvent, CAL_VALUE_LST_EXCEPTION_DATE, list)) { + if (value) { + calendar_svc_value_free(&value); + } + ThrowMsg(PlatformException, "cannot save the exception list"); + } + calendar_svc_update(m_platformEvent); + m_abstractEvent->getRecurrenceRule()->getExceptions().push_back(recurrenceId); + LogDebug("The recurring event is updated."); + } +} + +void EventWrapper::createEventFromString(std::string value) +{ + if (value.empty()) { + ThrowMsg(NullPointerException, + "Failed to create event from string"); + } else { + LogInfo("string to convert: "< + getDescription().c_str())) + { + ThrowMsg(PlatformException, "Can't set event description."); + } +} + +void EventWrapper::setSummaryToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + if (CAL_SUCCESS != calendar_svc_struct_set_str(m_platformEvent, + CAL_VALUE_TXT_SUMMARY, + m_abstractEvent->getSubject() + .c_str())) { + ThrowMsg(PlatformException, "Can't set event subject."); + } +} + +void EventWrapper::setStartTimeToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + time_t time = m_abstractEvent->getStartTime(); + if (time == 0) { + time = m_abstractEvent->getEndTime(); + } + if (CAL_SUCCESS != calendar_svc_struct_set_time(m_platformEvent, + CAL_VALUE_GMT_START_DATE_TIME, + CAL_TZ_FLAG_GMT, time)) { + ThrowMsg(PlatformException, "Can't set event start time."); + } + + const char* timeZone = m_abstractEvent->getTimeZone().c_str(); + if (CAL_SUCCESS != calendar_svc_struct_set_str(m_platformEvent, + CAL_VALUE_TXT_TZ_NAME, + timeZone)) { + ThrowMsg(PlatformException, "Can't set event time zone."); + } +} + +void EventWrapper::setEndTimeToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + time_t time = m_abstractEvent->getEndTime(); + if (time == 0) { + time = m_abstractEvent->getStartTime(); + } + if (CAL_SUCCESS != calendar_svc_struct_set_time(m_platformEvent, + CAL_VALUE_GMT_END_DATE_TIME, + CAL_TZ_FLAG_GMT, time)) { + ThrowMsg(PlatformException, "Can't set event end time."); + } +} + +void EventWrapper::setLocationToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + if (CAL_SUCCESS != calendar_svc_struct_set_str(m_platformEvent, + CAL_VALUE_TXT_LOCATION, + m_abstractEvent->getLocation() + .c_str())) { + ThrowMsg(PlatformException, "Can't set event location."); + } +} + +void convertDaysOfTheWeekToFlag(std::vector daysOfTheWeek, char weekFlag[]) +{ + for( unsigned int i=0; igetRecurrenceRule(); + if (NULL==rrule) { + LogInfo("rrule is not set."); + return; + } + + // set the recurrency frequency + switch (rrule->getFrequency()) { + case EventRecurrenceRule::NO_RECURRENCE: + ret = (CAL_SUCCESS == calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_REPEAT_TERM, + CAL_REPEAT_NONE)); + break; + case EventRecurrenceRule::DAILY_RECURRENCE: + ret = (CAL_SUCCESS == calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_REPEAT_TERM, + CAL_REPEAT_EVERY_DAY)); + break; + case EventRecurrenceRule::WEEKLY_RECURRENCE: + { + char weekFlag[] = "0000000"; + + if( 0 != rrule->getDaysOfTheWeek().size() ) { + convertDaysOfTheWeekToFlag(rrule->getDaysOfTheWeek(), weekFlag); + } else { + time_t date = m_abstractEvent->getStartTime(); + tm* time = localtime(&date); + if (!time) { + LogError("localtime failed"); + ret = -1; + break; + } + + int days = time->tm_wday; + if (days < 0 || days > 6) { + LogError("invalid week day"); + ret = -1; + } + weekFlag[days] = '1'; + } + + ret = (CAL_SUCCESS == calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_REPEAT_TERM, + CAL_REPEAT_EVERY_WEEK)) + && + (CAL_SUCCESS == calendar_svc_struct_set_str(m_platformEvent, + CAL_VALUE_TXT_WEEK_FLAG, + weekFlag)); + + LogInfo("Applied weekFlag "<getDaysOfTheWeek().size() ) { + convertDaysOfTheWeekToFlag(rrule->getDaysOfTheWeek(), weekFlag); + } else { + time_t date = m_abstractEvent->getStartTime(); + int days = localtime(&date)->tm_wday; + if (days < 0 || days > 6) { + LogError("invalid week day"); + ret = -1; + } else { + weekFlag[days] = '1'; + } + } + + ret = (CAL_SUCCESS == calendar_svc_struct_set_str(m_platformEvent, + CAL_VALUE_TXT_WEEK_FLAG, + weekFlag)); + LogInfo("Applied weekFlag "<getDaysOfTheWeek().size() ) { + convertDaysOfTheWeekToFlag(rrule->getDaysOfTheWeek(), weekFlag); + } else { + time_t date = m_abstractEvent->getStartTime(); + int days = localtime(&date)->tm_wday; + if (days < 0 || days > 6) { + LogError("invalid week day"); + ret = -1; + } else { + weekFlag[days] = '1'; + } + } + + ret = (CAL_SUCCESS == calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_REPEAT_TERM, + CAL_REPEAT_EVERY_MONTH)) + && + (CAL_SUCCESS == calendar_svc_struct_set_str(m_platformEvent, + CAL_VALUE_TXT_WEEK_FLAG, + weekFlag)); + LogInfo("Applied weekFlag "<getDaysOfTheWeek().size() ) { + convertDaysOfTheWeekToFlag(rrule->getDaysOfTheWeek(), weekFlag); + } else { + time_t date = m_abstractEvent->getStartTime(); + int days = localtime(&date)->tm_wday; + if (days < 0 || days > 6) { + LogError("invalid week day"); + ret = -1; + } else { + weekFlag[days] = '1'; + } + } + + ret = (CAL_SUCCESS == calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_REPEAT_TERM, + CAL_REPEAT_EVERY_YEAR)) + && + (CAL_SUCCESS == calendar_svc_struct_set_str(m_platformEvent, + CAL_VALUE_TXT_WEEK_FLAG, + weekFlag)); + LogInfo("Applied weekFlag "<getFrequency()); + ret = 0; + break; + } + + // set the recurrency interval + if (CAL_SUCCESS != calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_REPEAT_INTERVAL, + rrule->getInterval())) + { + ThrowMsg(PlatformException, "Can't set interval."); + ret = 0; + } + + // set the ocurrence count + if (-1 != rrule->getOccurrenceCount()) { + if (CAL_SUCCESS != calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_REPEAT_OCCURRENCES, + rrule->getOccurrenceCount())) + { + ThrowMsg(PlatformException, "Can't set occurrence count."); + ret = 0; + } + } else { + if (CAL_SUCCESS != calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_REPEAT_OCCURRENCES, + 0)) + { + ThrowMsg(PlatformException, "Can't set the ocurrence count."); + ret = 0; + } + } + + // set the recurrence end date + if (rrule->isEndDateSet()) { + if (CAL_SUCCESS != calendar_svc_struct_set_time( + m_platformEvent, + CAL_VALUE_GMT_REPEAT_END_DATE, + CAL_TZ_FLAG_GMT, + m_abstractEvent->getRecurrenceRule()->getEndDate())) + { + ThrowMsg(PlatformException, "Can't set recurrence end date."); + ret = 0; + } + } else { + // Platform needs default positive end date in the sql query statement for the recurrence event! + if (CAL_SUCCESS != calendar_svc_struct_set_time( + m_platformEvent, + CAL_VALUE_GMT_REPEAT_END_DATE, + CAL_TZ_FLAG_GMT, + 1)) + { + ThrowMsg(PlatformException, "Can't set recurrence end date."); + ret = 0; + } + } + + // set the exceptions + if ( !rrule->getExceptions().empty() ) + { + LogInfo("Set the exceptions."); + GList* list = NULL; + calendar_svc_struct_get_list(m_platformEvent, CAL_VALUE_LST_EXCEPTION_DATE, &list); + + for( unsigned int i=0; igetExceptions().size(); i++ ) + { + cal_value *value = calendar_svc_value_new(CAL_VALUE_LST_EXCEPTION_DATE); + if ( CAL_SUCCESS!=calendar_svc_value_set_time(value, + CAL_VALUE_GMT_EXCEPTION_DATE_TIME, + CAL_TZ_FLAG_GMT, + rrule->getExceptions().at(i)) ) { + if (value) { + calendar_svc_value_free(&value); + } + ThrowMsg(PlatformException, "cannot save the exception time event"); + } + + list = g_list_append(list, value); + } + if (CAL_SUCCESS!=calendar_svc_struct_store_list(m_platformEvent, CAL_VALUE_LST_EXCEPTION_DATE, list)) { + ThrowMsg(PlatformException, "cannot save the exceptions"); + } + } + + // "day_date" flag means the day of week by 0 and the date of month by 1 based on the start date, + // which takes effects in monthly/yearly repeat term. + if( true == rrule->getSetPosition() ) { + if (CAL_SUCCESS != calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_DAY_DATE, + 0)) + { + ThrowMsg(PlatformException, "Can't set the day date."); + ret = 0; + } + } else { + if (CAL_SUCCESS != calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_DAY_DATE, + 1)) + { + ThrowMsg(PlatformException, "Can't set the day date."); + ret = 0; + } + } + + if (!ret) { + ThrowMsg(PlatformException, "Can't set event recurrence rule."); + } +} + +void EventWrapper::setAlarmsToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + if( 0 != m_abstractEvent->getAlarmsTick().size() ) { + LogInfo("Set the alarms."); + GList* list = NULL; + calendar_svc_struct_get_list(m_platformEvent, CAL_VALUE_LST_ALARM, &list); + + for( unsigned int i=0; igetAlarmsTick().size(); i++ ) + { + cal_value *value = calendar_svc_value_new(CAL_VALUE_LST_ALARM); + + // We have to use alarm tick and tick unit for alarm creation. + int errorCode = calendar_svc_value_set_int( + value, + CAL_VALUE_INT_ALARMS_TICK, + m_abstractEvent->getAlarmsTick().at(i)); + if (CAL_SUCCESS != errorCode) { + if (value) { + calendar_svc_value_free(&value); + } + LogError("Can't set CAL_VALUE_INT_ALARMS_TICK, error: " << errorCode); + ThrowMsg(PlatformException, "Can't set alarm tick."); + } + errorCode = calendar_svc_value_set_int( + value, + CAL_VALUE_INT_ALARMS_TICK_UNIT, + CAL_SCH_TIME_UNIT_MIN); + if (CAL_SUCCESS != errorCode) { + if (value) { + calendar_svc_value_free(&value); + } + LogError("Can't set CAL_VALUE_INT_ALARMS_TICK_UNIT, error: " << errorCode); + ThrowMsg(PlatformException, "Can't set alarm tick unit."); + } + + // Set the alarm type. + cal_alert_type_t alarmType = CAL_ALERT_MELODY; + switch (m_abstractEvent->getAlarmsType().at(i)) { + case CalendarEvent::NO_ALARM: + alarmType = CAL_ALERT_MUTE; + break; + case CalendarEvent::SOUND_ALARM: + alarmType = CAL_ALERT_MELODY; + break; + case CalendarEvent::SILENT_ALARM: + alarmType = CAL_ALERT_VIBRATION; + break; + default: + LogDebug("Use the default alarm type"); + break; + } + errorCode = calendar_svc_value_set_int( + value, + CAL_VALUE_INT_ALARMS_TYPE, + alarmType); + if (CAL_SUCCESS != errorCode) { + if (value) { + calendar_svc_value_free(&value); + } + LogError("Can't set CAL_VALUE_INT_ALARMS_TYPE, error: " << errorCode); + ThrowMsg(PlatformException, "Can't set alarm type."); + } + + list = g_list_append(list, value); + } + + if (CAL_SUCCESS!=calendar_svc_struct_store_list(m_platformEvent, CAL_VALUE_LST_ALARM, list)) { + ThrowMsg(PlatformException, "cannot save the alarms"); + } + } +} + +void EventWrapper::setStatusToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + cals_status_t status = CALS_STATUS_NONE; + + switch (m_abstractEvent->getStatus()) { + case CalendarEvent::TENTATIVE_STATUS: + status = CALS_EVENT_STATUS_TENTATIVE; + break; + case CalendarEvent::CONFIRMED_STATUS: + status = CALS_EVENT_STATUS_CONFIRMED; + break; + case CalendarEvent::CANCELLED_STATUS: + status = CALS_EVENT_STATUS_CANCELLED; + break; + case CalendarEvent::NEEDS_ACTION_STATUS: + status = CALS_TODO_STATUS_NEEDS_ACTION; + break; + case CalendarEvent::COMPLETED_STATUS: + status = CALS_TODO_STATUS_COMPLETED; + break; + case CalendarEvent::IN_PROCESS_STATUS: + status = CALS_TODO_STATUS_IN_PROCESS; + break; + default: + status = CALS_STATUS_NONE; + break; + } + + if (CAL_SUCCESS != calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_TASK_STATUS, + status)) { + ThrowMsg(PlatformException, "Can't set event status."); + } +} + +void EventWrapper::setCategoriesToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + GList *categoryList = NULL; + cal_value* category = NULL; + Try + { + for (size_t i = 0; i < m_abstractEvent->getCategories()->size(); ++i) { + LogDebug("adding category " << + m_abstractEvent->getCategories()->at(i)); + category = calendar_svc_value_new(CAL_VALUE_LST_MEETING_CATEGORY); + if (NULL == category) { + LogError("error during creating category"); + ThrowMsg(PlatformException, + "Cannot create category object"); + } + if (CAL_SUCCESS != + calendar_svc_value_set_str(category, "category_name", + m_abstractEvent->getCategories()->at( + i).c_str())) { + LogError("error during setting category name"); + calendar_svc_value_free(&category); + ThrowMsg(PlatformException, "Cannot set category name"); + } + //Order of categories is lost during saving, so we don't need to reverse this list. + categoryList = g_list_prepend(categoryList, category); + } + + calendar_svc_struct_store_list(m_platformEvent, + CAL_VALUE_LST_MEETING_CATEGORY, + categoryList); + } + Catch(PlatformException) + { + LogError("error during setting categories"); + calendar_svc_struct_store_list(m_platformEvent, + CAL_VALUE_LST_MEETING_CATEGORY, + NULL); + for (; categoryList; categoryList = g_list_next(categoryList)) { + category = static_cast(categoryList->data); + calendar_svc_value_free(&category); + } + g_list_free(categoryList); + ReThrow(PlatformException); + } +} + +void EventWrapper::setIDToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + if (m_abstractEvent->getIdIsSet()) { + if (CAL_SUCCESS != calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_INDEX, + m_abstractEvent->getId())) + { + ThrowMsg(PlatformException, "Can't set event ID."); + } + } else { + if (CAL_SUCCESS != calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_INDEX, + NEW_EVENT_ID)) { + ThrowMsg(PlatformException, "Can't set event ID."); + } + } +} + +void EventWrapper::setIsAllDayToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + if (CAL_SUCCESS != calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_ALL_DAY_EVENT, + m_abstractEvent->getIsAllDay())) { + ThrowMsg(PlatformException, "Can't set event isAllDay."); + } +} + +void EventWrapper::setOrganizerToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + if (CAL_SUCCESS != calendar_svc_struct_set_str(m_platformEvent, + CAL_VALUE_TXT_ORGANIZER_NAME, + m_abstractEvent->getOrganizer().c_str())) { + ThrowMsg(PlatformException, "Can't set event organizer."); + } +} + +void EventWrapper::setLastModifiedDateToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + time_t time = m_abstractEvent->getLastModifiedDate(); + + if (CAL_SUCCESS != calendar_svc_struct_set_time(m_platformEvent, + CAL_VALUE_GMT_LAST_MODIFIED_TIME, + CAL_TZ_FLAG_GMT, time)) { + ThrowMsg(PlatformException, "Can't set event lastModifiedDate."); + } +} + +void EventWrapper::setVisibilityToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + int visibility = PUBLIC_VISIBILITY; // default value + switch (m_abstractEvent->getVisibility()) { + case CalendarEvent::PUBLIC_VISIBILITY: + visibility = PUBLIC_VISIBILITY; + break; + case CalendarEvent::PRIVATE_VISIBILITY: + visibility = PRIVATE_VISIBILITY; + break; + case CalendarEvent::CONFIDENTIAL_VISIBILITY: + visibility = CONFIDENTIAL_VISIBILITY; + break; + default: + LogDebug("Use the default visibility"); + break; + } + if (CAL_SUCCESS != calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_SENSITIVITY, + visibility)) { + ThrowMsg(PlatformException, "Can't set visibility."); + } +} + +void EventWrapper::setAvailabilityToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + cal_event_availability_type_t availability = EVENT_FREE_FB; + switch (m_abstractEvent->getAvailability()) { + case CalendarEvent::BUSY_FB: + availability = EVENT_BUSY_FB; + break; + case CalendarEvent::BUSY_UNAVAILABLE_FB: + availability = EVENT_BUSY_UNAVAILABLE_FB; + break; + case CalendarEvent::FREE_FB: + availability = EVENT_FREE_FB; + break; + case CalendarEvent::BUSY_TENTATIVE_FB: + availability = EVENT_BUSY_TENTATIVE_FB; + break; + default: + LogDebug("Use the default availability"); + break; + } + if (CAL_SUCCESS != calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_AVAILABILITY, + availability)) { + ThrowMsg(PlatformException, "Can't set availability."); + } +} + +void EventWrapper::setUIdToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + if (CAL_SUCCESS != calendar_svc_struct_set_str(m_platformEvent, + CAL_VALUE_TXT_UID, + m_abstractEvent->getUId().c_str())) { + ThrowMsg(PlatformException, "Can't set event uid."); + } +} + +void EventWrapper::setAttendeesToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + EventAttendeeListPtr attendeeList = m_abstractEvent->getAttendees(); + if (NULL==attendeeList) { + LogInfo("attendeeList is not set."); + return; + } + + GList *attendees = NULL; + cal_value* attendee = NULL; + Try + { + for (size_t i = 0; i < attendeeList->size(); ++i) { + LogDebug("adding attendee " << i+1 << " over " << + attendeeList->size()); + + attendee = calendar_svc_value_new(CAL_VALUE_LST_ATTENDEE_LIST); + if (NULL == attendee) { + LogError("error during creating attendee"); + ThrowMsg(PlatformException, + "Cannot create attendee object"); + } + + // save name + if (CAL_SUCCESS != + calendar_svc_value_set_str(attendee, CAL_VALUE_TXT_ATTENDEE_DETAIL_NAME, + attendeeList->at(i)->getName().c_str())) { + LogError("error during setting attendee name"); + calendar_svc_value_free(&attendee); + ThrowMsg(PlatformException, "Cannot set attendee name"); + } + + // save uri + if (CAL_SUCCESS != + calendar_svc_value_set_str(attendee, CAL_VALUE_TXT_ATTENDEE_DETAIL_EMAIL, + attendeeList->at(i)->getURI().c_str())) { + LogError("error during setting attendee URI"); + calendar_svc_value_free(&attendee); + ThrowMsg(PlatformException, "Cannot set attendee URI"); + } + + // save role + cal_event_attendee_role_type_t role = EVENT_ATTENDEE_CHAIR_ROLE; + switch (attendeeList->at(i)->getRole()) { + case EventAttendee::REQ_PARTICIPANT_ROLE: + role = EVENT_ATTENDEE_REQ_PARTICIPANT_ROLE; + break; + case EventAttendee::OPT_PARTICIPANT_ROLE: + role = EVENT_ATTENDEE_OPT_PARTICIPANT_ROLE; + break; + case EventAttendee::NON_PARTICIPANT_ROLE: + role = EVENT_ATTENDEE_NON_PARTICIPANT_ROLE; + break; + case EventAttendee::CHAIR_ROLE: + role = EVENT_ATTENDEE_CHAIR_ROLE; + break; + default: + LogDebug("Use the default role"); + break; + } + if (CAL_SUCCESS != + calendar_svc_value_set_int(attendee, CAL_VALUE_INT_ATTENDEE_ROLE, + role)) { + LogError("error during setting attendee role"); + calendar_svc_value_free(&attendee); + ThrowMsg(PlatformException, "Cannot set attendee role"); + } + + // save status + cal_event_attendee_status_type_t status = EVENT_ATTENDEE_PENDING_AT_STATUS; + switch (attendeeList->at(i)->getStatus()) { + case EventAttendee::PENDING_AT_STATUS: + status = EVENT_ATTENDEE_PENDING_AT_STATUS; + break; + case EventAttendee::ACCEPTED_AT_STATUS: + status = EVENT_ATTENDEE_ACCEPTED_AT_STATUS; + break; + case EventAttendee::DECLINED_AT_STATUS: + status = EVENT_ATTENDEE_DECLINED_AT_STATUS; + break; + case EventAttendee::TENTATIVE_AT_STATUS: + status = EVENT_ATTENDEE_TENTATIVE_AT_STATUS; + break; + case EventAttendee::DELEGATED_AT_STATUS: + status = EVENT_ATTENDEE_DELEGATED_AT_STATUS; + break; + case EventAttendee::COMPLETED_AT_STATUS: + status = EVENT_ATTENDEE_COMPLETED_AT_STATUS; + break; + case EventAttendee::IN_PROCESS_AT_STATUS: + status = EVENT_ATTENDEE_IN_PROCESS_AT_STATUS; + break; + default: + LogDebug("Use the default status"); + break; + } + if (CAL_SUCCESS != + calendar_svc_value_set_int(attendee, CAL_VALUE_INT_ATTENDEE_DETAIL_STATUS, + status)) { + LogError("error during setting attendee status"); + calendar_svc_value_free(&attendee); + ThrowMsg(PlatformException, "Cannot set attendee status"); + } + + // save RSVP + if (CAL_SUCCESS != + calendar_svc_value_set_int(attendee, CAL_VALUE_INT_ATTENDEE_RSVP, + attendeeList->at(i)->getRSVP())) { + LogError("error during setting attendee RSVP"); + calendar_svc_value_free(&attendee); + ThrowMsg(PlatformException, "Cannot set attendee RSVP"); + } + + // save type + cal_event_attendee_type_t type = EVENT_ATTENDEE_INDIVIDUAL_TYPE; + switch (attendeeList->at(i)->getType()) { + case EventAttendee::INDIVIDUAL_TYPE: + type = EVENT_ATTENDEE_INDIVIDUAL_TYPE; + break; + case EventAttendee::GROUP_TYPE: + type = EVENT_ATTENDEE_GROUP_TYPE; + break; + case EventAttendee::RESOURCE_TYPE: + type = EVENT_ATTENDEE_RESOURCE_TYPE; + break; + case EventAttendee::ROOM_TYPE: + type = EVENT_ATTENDEE_ROOM_TYPE; + break; + case EventAttendee::UNKNOWN_TYPE: + type = EVENT_ATTENDEE_UNKNOWN_TYPE; + break; + default: + LogDebug("Use the default type"); + break; + } + if (CAL_SUCCESS != + calendar_svc_value_set_int(attendee, CAL_VALUE_INT_ATTENDEE_DETAIL_TYPE, + type)) { + LogError("error during setting attendee type"); + calendar_svc_value_free(&attendee); + ThrowMsg(PlatformException, "Cannot set attendee type"); + } + + // save group + if (CAL_SUCCESS != + calendar_svc_value_set_str(attendee, CAL_VALUE_TXT_ATTENDEE_GROUP, + attendeeList->at(i)->getGroup().c_str())) { + LogError("error during setting attendee group"); + calendar_svc_value_free(&attendee); + ThrowMsg(PlatformException, "Cannot set attendee group"); + } + + // save delegatorURI + if (CAL_SUCCESS != + calendar_svc_value_set_str(attendee, CAL_VALUE_TXT_ATTENDEE_DELEGATOR_URI, + attendeeList->at(i)->getDelegatorURI().c_str())) { + LogError("error during setting attendee delegator uri"); + calendar_svc_value_free(&attendee); + ThrowMsg(PlatformException, "Cannot set attendee delegator uri"); + } + + // save delegateURI + if (CAL_SUCCESS != + calendar_svc_value_set_str(attendee, CAL_VALUE_TXT_ATTENDEE_DELEGATE_URI, + attendeeList->at(i)->getDelegateURI().c_str())) { + LogError("error during setting attendee delegate uri"); + calendar_svc_value_free(&attendee); + ThrowMsg(PlatformException, "Cannot set attendee delegate uri"); + } + + // save uid + if (CAL_SUCCESS != + calendar_svc_value_set_str(attendee, CAL_VALUE_TXT_ATTENDEE_UID, + attendeeList->at(i)->getPersonId().c_str())) { + LogError("error during setting attendee uid"); + calendar_svc_value_free(&attendee); + ThrowMsg(PlatformException, "Cannot set attendee uid"); + } + + attendees = g_list_append(attendees, attendee); + } + + LogDebug("m_abstractEvent->getAttendees()->size() " << attendeeList->size()); + + calendar_svc_struct_store_list(m_platformEvent, + CAL_VALUE_LST_ATTENDEE_LIST, + attendees); + } + Catch(PlatformException) + { + LogError("error during setting attendees"); + calendar_svc_struct_store_list(m_platformEvent, + CAL_VALUE_LST_ATTENDEE_LIST, + NULL); + for (; attendees; attendees = g_list_next(attendees)) { + attendee = static_cast(attendees->data); + calendar_svc_value_free(&attendee); + } + g_list_free(attendees); + ReThrow(PlatformException); + } +} + +void EventWrapper::setPositionToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + if (CAL_SUCCESS != calendar_svc_struct_set_double(m_platformEvent, + CAL_VALUE_DBL_LATITUDE, + m_abstractEvent->getLatitude())) { + ThrowMsg(PlatformException, "Can't set latitude."); + } + + if (CAL_SUCCESS != calendar_svc_struct_set_double(m_platformEvent, + CAL_VALUE_DBL_LONGITUDE, + m_abstractEvent->getLongitude())) { + ThrowMsg(PlatformException, "Can't set longitude."); + } +} + +void EventWrapper::setPriorityToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + cal_priority_type_t priority = (cal_priority_type_t)-1; + + switch (m_abstractEvent->getPriority()) { + case CalendarEvent::HIGH_PRIORITY: + priority = EVENT_PRIORITY_HIGH; + break; + case CalendarEvent::MEDIUM_PRIORITY: + priority = EVENT_PRIORITY_NORMAL; + break; + case CalendarEvent::LOW_PRIORITY: + priority = EVENT_PRIORITY_LOW; + break; + default: + break; + } + + if (CAL_SUCCESS != calendar_svc_struct_set_int(m_platformEvent, + CAL_VALUE_INT_PRIORITY, + priority)) + { + ThrowMsg(PlatformException, "Can't set task priority."); + } +} + +void EventWrapper::setCreatedDateToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + +// calendar F/W not supported +// time_t time = m_abstractEvent->getCreatedDate(); +// if (CAL_SUCCESS != calendar_svc_struct_set_time(m_platformTask, +// CAL_VALUE_GMT_CREATED_DATE_TIME, +// CAL_TZ_FLAG_GMT, +// time)) { +// ThrowMsg(PlatformException, "Can't set created time."); +// } +} + +void EventWrapper::setCompletedDateToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + +// calendar F/W not supported +// time_t time = m_abstractEvent->getCompletedDate(); +// if (CAL_SUCCESS != calendar_svc_struct_set_time(m_platformEvent, +// CAL_VALUE_GMT_COMPLETED_DATE_TIME, +// CAL_TZ_FLAG_GMT, +// time)) { +// ThrowMsg(PlatformException, "Can't set task completed time."); +// } +} + +void EventWrapper::setProgressToPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + +// int progress = m_abstractEvent->getProgress(); +// not supported +// if (CAL_SUCCESS != calendar_svc_struct_set_int(m_platformEvent, +// CAL_VALUE_INT_PROGRESS, +// progress)) { +// ThrowMsg(PlatformException, "Can't set visibility."); +// } +} + +CalendarEventPtr EventWrapper::convertPlatformEventToAbstractEvent() +{ + LogDebug("entered"); + setDescriptionFromPlatformEvent(); + setSummaryFromPlatformEvent(); + setStartTimeFromPlatformEvent(); + setEndTimeFromPlatformEvent(); // replace for duration + setLocationFromPlatformEvent(); + setCategoriesFromPlatformEvent(); + setStatusFromPlatformEvent(); + setAlarmsFromPlatformEvent(); + setIsAllDayFromPlatformEvent(); + setOrganizerFromPlatformEvent(); + setAttendeesFromPlatformEvent(); + setPositionFromPlatformEvent(); + setVisibilityFromPlatformEvent(); + setLastModifiedDateFromPlatformEvent(); + setAvailabilityFromPlatformEvent(); + setRecurrenceRuleFromPlatformEvent(); + setIDFromPlatformEvent(); + //setUIdFromPlatformEvent(); // We set the uid value as the same with id. + //setRecurrenceIdFromPlatformEvent(); + setPriorityFromPlatformEvent(); + setCreatedDateFromPlatformEvent(); + setCompletedDateFromPlatformEvent(); + setProgressFromPlatformEvent(); + + return getAbstractEvent(); +} + +void EventWrapper::setDescriptionFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + const char *description = calendar_svc_struct_get_str( + m_platformEvent, + CAL_VALUE_TXT_DESCRIPTION); + if (description) { + m_abstractEvent->setDescription(description); + } +} + +void EventWrapper::setSummaryFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + const char *summary = calendar_svc_struct_get_str(m_platformEvent, + CAL_VALUE_TXT_SUMMARY); + if (summary) { + m_abstractEvent->setSubject(summary); + } +} + +void EventWrapper::setStartTimeFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + time_t startTime = calendar_svc_struct_get_time( + m_platformEvent, + CAL_VALUE_GMT_START_DATE_TIME, + CAL_TZ_FLAG_GMT); + m_abstractEvent->setStartTime(startTime); + + // Retrive the time zone info only when the start time is loaded. + char* timeZone = calendar_svc_struct_get_str( + m_platformEvent, + CAL_VALUE_TXT_TZ_NAME); + if( timeZone ) { + m_abstractEvent->setTimeZone(std::string(timeZone)); + } +} + +void EventWrapper::setEndTimeFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + time_t endTime = calendar_svc_struct_get_time(m_platformEvent, + CAL_VALUE_GMT_END_DATE_TIME, + CAL_TZ_FLAG_GMT); + m_abstractEvent->setEndTime(endTime); +} + +void EventWrapper::setLocationFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + const char* location = calendar_svc_struct_get_str(m_platformEvent, + CAL_VALUE_TXT_LOCATION); + if (location) { + m_abstractEvent->setLocation(location); + } +} + +std::vector convertFlagToDaysOfTheWeek(const char *daysFlag) +{ + if( strlen(daysFlag)<7 ) + LogError("daysFlag is too short!"); + + std::vector daysOfTheWeek; + + if( daysFlag[0]=='1' ) + daysOfTheWeek.push_back("SU"); + if( daysFlag[1]=='1' ) + daysOfTheWeek.push_back("MO"); + if( daysFlag[2]=='1' ) + daysOfTheWeek.push_back("TU"); + if( daysFlag[3]=='1' ) + daysOfTheWeek.push_back("WE"); + if( daysFlag[4]=='1' ) + daysOfTheWeek.push_back("TH"); + if( daysFlag[5]=='1' ) + daysOfTheWeek.push_back("FR"); + if( daysFlag[6]=='1' ) + daysOfTheWeek.push_back("SA"); + + return daysOfTheWeek; +} + +void EventWrapper::setRecurrenceRuleFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + EventRecurrenceRulePtr rrule(new EventRecurrenceRule()); + + // load the recurrence frequency and daysOfTheWeek + int frequency = calendar_svc_struct_get_int(m_platformEvent, + CAL_VALUE_INT_REPEAT_TERM); + LogInfo("frequency "<setFrequency(EventRecurrenceRule::NO_RECURRENCE); + break; + case CAL_REPEAT_EVERY_DAY: + rrule->setFrequency(EventRecurrenceRule::DAILY_RECURRENCE); + break; + case CAL_REPEAT_EVERY_WEEK: + { + const char *daysFlag = calendar_svc_struct_get_str( + m_platformEvent, + CAL_VALUE_TXT_WEEK_FLAG); + if (daysFlag && strncmp(daysFlag, WEEKDAYS, 7) == 0) { + rrule->setFrequency(EventRecurrenceRule::WEEKDAY_RECURRENCE); + } else { + rrule->setFrequency(EventRecurrenceRule::WEEKLY_RECURRENCE); + } + + std::vector daysOfTheWeek = convertFlagToDaysOfTheWeek(daysFlag); + rrule->setDaysOfTheWeek(daysOfTheWeek); + } + break; + case CAL_REPEAT_EVERY_MONTH: + { + const char *daysFlag = calendar_svc_struct_get_str( + m_platformEvent, + CAL_VALUE_TXT_WEEK_FLAG); + if (!daysFlag || strnlen(daysFlag, 7) == 0) { + rrule->setFrequency(EventRecurrenceRule::MONTHLY_RECURRENCE); + } else { + rrule->setFrequency(EventRecurrenceRule::MONTHLY_ON_DAY_RECURRENCE); + } + + std::vector daysOfTheWeek = convertFlagToDaysOfTheWeek(daysFlag); + rrule->setDaysOfTheWeek(daysOfTheWeek); + } + break; + case CAL_REPEAT_EVERY_YEAR: + { + const char *daysFlag = calendar_svc_struct_get_str( + m_platformEvent, + CAL_VALUE_TXT_WEEK_FLAG); + rrule->setFrequency(EventRecurrenceRule::YEARLY_RECURRENCE); + + std::vector daysOfTheWeek = convertFlagToDaysOfTheWeek(daysFlag); + rrule->setDaysOfTheWeek(daysOfTheWeek); + } + break; + default: + LogWarning("unknown recurrence"); + rrule->setFrequency(EventRecurrenceRule::NO_RECURRENCE); + break; + } + + // load the recurrence interval + int interval = calendar_svc_struct_get_int(m_platformEvent, + CAL_VALUE_INT_REPEAT_INTERVAL); + rrule->setInterval(interval); + + // load the ocurrence count + int occurrrenceCount = calendar_svc_struct_get_int(m_platformEvent, + CAL_VALUE_INT_REPEAT_OCCURRENCES); + rrule->setOccurrenceCount(occurrrenceCount); + + // load the recurrence end date + time_t endDate = calendar_svc_struct_get_time(m_platformEvent, + CAL_VALUE_GMT_REPEAT_END_DATE, + CAL_TZ_FLAG_GMT); + rrule->setEndDate(endDate); + + // load the exceptions + rrule->getExceptions().clear(); + GList* exceptionList = NULL; + calendar_svc_struct_get_list(m_platformEvent, CAL_VALUE_LST_EXCEPTION_DATE, &exceptionList); + cal_value* exceptionValue = NULL; + for (; exceptionList; exceptionList = g_list_next(exceptionList)) { + exceptionValue = static_cast(exceptionList->data); + std::time_t exceptoinTime = calendar_svc_value_get_time(exceptionValue, + CAL_VALUE_GMT_EXCEPTION_DATE_TIME, + CAL_TZ_FLAG_GMT); + if (CAL_ERR_FAIL == exceptoinTime) { + LogError("cannot read exceptoin time"); + return; + } + rrule->getExceptions().push_back(exceptoinTime); + } + + // load the setPosition + int day_date = calendar_svc_struct_get_int(m_platformEvent, + CAL_VALUE_INT_DAY_DATE); + if( 0 == day_date ) { + rrule->setSetPosition(true); + } else { + rrule->setSetPosition(false); + } + + // set the loaded recurrence rule + m_abstractEvent->setRecurrenceRule(rrule); +} + +void EventWrapper::setAlarmsFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + GList* alarmList = NULL; + calendar_svc_struct_get_list(m_platformEvent, CAL_VALUE_LST_ALARM, &alarmList); + cal_value* alarmValue = NULL; + for (; alarmList; alarmList = g_list_next(alarmList)) { + alarmValue = static_cast(alarmList->data); + + int tick = calendar_svc_value_get_int(alarmValue, CAL_VALUE_INT_ALARMS_TICK); + if (CAL_ERR_FAIL == tick) { + LogError("cannot read alarm tick"); + return; + } + m_abstractEvent->getAlarmsTick().push_back(tick); + + cal_alert_type_t type = static_cast(calendar_svc_value_get_int(alarmValue, CAL_VALUE_INT_ALARMS_TYPE)); + if ( 0 > type) { + LogError("cannot read alarm type"); + return; + } + switch (type) { + case CAL_ALERT_VIBRATION: + m_abstractEvent->getAlarmsType().push_back(CalendarEvent::SILENT_ALARM); + break; + case CAL_ALERT_MELODY: + case CAL_ALERT_INCREASING_MELODY: + case CAL_ALERT_VIBRATION_THEN_MELODY: + case CAL_ALERT_VIBMELODY: + case CAL_ALERT_VIB_INCREASING_MELODY: + m_abstractEvent->getAlarmsType().push_back(CalendarEvent::SOUND_ALARM); + break; + case CAL_ALERT_MUTE: + default: + m_abstractEvent->getAlarmsType().push_back(CalendarEvent::NO_ALARM); + break; + } + } +} + +void EventWrapper::setStatusFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + cals_status_t status = static_cast(calendar_svc_struct_get_int(m_platformEvent, + CAL_VALUE_INT_TASK_STATUS)); + switch (status) { + case CALS_EVENT_STATUS_TENTATIVE: + m_abstractEvent->setStatus(CalendarEvent::TENTATIVE_STATUS); + break; + case CALS_EVENT_STATUS_CONFIRMED: + m_abstractEvent->setStatus(CalendarEvent::CONFIRMED_STATUS); + break; + case CALS_EVENT_STATUS_CANCELLED: + case CALS_TODO_STATUS_CANCELLED: + m_abstractEvent->setStatus(CalendarEvent::CANCELLED_STATUS); + break; + case CALS_TODO_STATUS_NEEDS_ACTION: + m_abstractEvent->setStatus(CalendarEvent::NEEDS_ACTION_STATUS); + break; + case CALS_TODO_STATUS_COMPLETED: + m_abstractEvent->setStatus(CalendarEvent::COMPLETED_STATUS); + break; + case CALS_TODO_STATUS_IN_PROCESS: + m_abstractEvent->setStatus(CalendarEvent::IN_PROCESS_STATUS); + break; + default: + m_abstractEvent->setStatus(CalendarEvent::UNDEFINED_STATUS); + break; + } +} + +void EventWrapper::setCategoriesFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + m_abstractEvent->getCategories()->clear(); + GList *categoryList = NULL; + if (CAL_SUCCESS != + calendar_svc_struct_get_list(m_platformEvent, + CAL_VALUE_LST_MEETING_CATEGORY, + &categoryList)) { + LogError("cannot read category list"); + return; + } + cal_value* category = NULL; + for (; categoryList; categoryList = g_list_next(categoryList)) { + category = static_cast(categoryList->data); + char* categoryName = calendar_svc_value_get_str(category, + "category_name"); + if (NULL == categoryName) { + LogError("cannot read category name"); + return; + } + m_abstractEvent->getCategories()->push_back(categoryName); + } +} + +void EventWrapper::setIDFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + m_abstractEvent->setId(getIDFromPlatformEvent()); + + // Set the uid here. + std::stringstream ss; + ss<setUId(ss.str()); +} + +void EventWrapper::setIsAllDayFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + int isAllDay = calendar_svc_struct_get_int(m_platformEvent, + CAL_VALUE_INT_ALL_DAY_EVENT); + m_abstractEvent->setIsAllDay(isAllDay); +} + +void EventWrapper::setOrganizerFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + const char* organizer = calendar_svc_struct_get_str(m_platformEvent, + CAL_VALUE_TXT_ORGANIZER_NAME); + if (organizer) { + m_abstractEvent->setOrganizer(organizer); + } +} + +void EventWrapper::setLastModifiedDateFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + time_t lastModifiedDate = calendar_svc_struct_get_time( + m_platformEvent, + CAL_VALUE_GMT_LAST_MODIFIED_TIME, + CAL_TZ_FLAG_GMT); + m_abstractEvent->setLastModifiedDate(lastModifiedDate); +} + +void EventWrapper::setVisibilityFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + int visibility = calendar_svc_struct_get_int(m_platformEvent, + CAL_VALUE_INT_SENSITIVITY); + switch (visibility) { + case PUBLIC_VISIBILITY: + m_abstractEvent->setVisibility(CalendarEvent::PUBLIC_VISIBILITY); + break; + case PRIVATE_VISIBILITY: + m_abstractEvent->setVisibility(CalendarEvent::PRIVATE_VISIBILITY); + break; + case CONFIDENTIAL_VISIBILITY: + m_abstractEvent->setVisibility(CalendarEvent::CONFIDENTIAL_VISIBILITY); + break; + default: + m_abstractEvent->setVisibility(CalendarEvent::PUBLIC_VISIBILITY); + break; + } +} + +void EventWrapper::setAvailabilityFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + cal_status_type_t availability = + static_cast(calendar_svc_struct_get_int( + m_platformEvent, + CAL_VALUE_INT_AVAILABILITY)); + switch (availability) { + case EVENT_BUSY_FB: + m_abstractEvent->setAvailability(CalendarEvent::BUSY_FB); + break; + case EVENT_BUSY_UNAVAILABLE_FB: + m_abstractEvent->setAvailability(CalendarEvent::BUSY_UNAVAILABLE_FB); + break; + case EVENT_FREE_FB: + m_abstractEvent->setAvailability(CalendarEvent::FREE_FB); + break; + case EVENT_BUSY_TENTATIVE_FB: + m_abstractEvent->setAvailability(CalendarEvent::BUSY_TENTATIVE_FB); + break; + default: + m_abstractEvent->setAvailability(CalendarEvent::FREE_FB); + break; + } +} + +void EventWrapper::setUIdFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + const char* uid = calendar_svc_struct_get_str(m_platformEvent, + CAL_VALUE_TXT_UID); + if (uid) { + m_abstractEvent->setUId(uid); + } +} + +void EventWrapper::setRecurrenceIdFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + if( (EventRecurrenceRule::DAILY_RECURRENCE <= m_abstractEvent->getRecurrenceRule()->getFrequency() && m_abstractEvent->getRecurrenceRule()->getFrequency() <= EventRecurrenceRule::MONTHLY_ON_DAY_RECURRENCE) ) { + time_t recurrenceID = calendar_svc_struct_get_time( + m_platformEvent, + CAL_VALUE_GMT_START_DATE_TIME, + CAL_TZ_FLAG_GMT); + m_abstractEvent->setRecurrenceId(recurrenceID); + } else { + m_abstractEvent->setRecurrenceId(0); + } +} + +void EventWrapper::setAttendeesFromPlatformEvent() +{ + LogDebug("entered"); + + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + if ( NULL != m_abstractEvent->getAttendees() ) + m_abstractEvent->getAttendees()->clear(); + + GList *attendees = NULL; + if (CAL_SUCCESS != + calendar_svc_struct_get_list(m_platformEvent, + CAL_VALUE_LST_ATTENDEE_LIST, + &attendees)) { + LogError("cannot read attendees list"); + return; + } + cal_value* attendee = NULL; + for (; attendees; attendees = g_list_next(attendees)) { + attendee = static_cast(attendees->data); + EventAttendeePtr attendeePtr(new EventAttendee()); + + // load name + char* attendeeName = calendar_svc_value_get_str(attendee, CAL_VALUE_TXT_ATTENDEE_DETAIL_NAME); + if (NULL == attendeeName) { + LogError("cannot read attendee name"); + return; + } + attendeePtr->setName(attendeeName); + + // load URI + char* attendeeURI = calendar_svc_value_get_str(attendee, CAL_VALUE_TXT_ATTENDEE_DETAIL_EMAIL); + if (NULL == attendeeURI) { + LogError("cannot read attendee URI"); + return; + } + attendeePtr->setURI(attendeeURI); + + // load role + cal_event_attendee_role_type_t attendeeRole = + static_cast(calendar_svc_struct_get_int( + m_platformEvent, + CAL_VALUE_INT_ATTENDEE_ROLE)); + if (0 > attendeeRole) { + LogError("cannot read attendee role"); + return; + } + switch (attendeeRole) { + case EVENT_ATTENDEE_REQ_PARTICIPANT_ROLE: + attendeePtr->setRole(EventAttendee::REQ_PARTICIPANT_ROLE); + break; + case EVENT_ATTENDEE_OPT_PARTICIPANT_ROLE: + attendeePtr->setRole(EventAttendee::OPT_PARTICIPANT_ROLE); + break; + case EVENT_ATTENDEE_NON_PARTICIPANT_ROLE: + attendeePtr->setRole(EventAttendee::NON_PARTICIPANT_ROLE); + break; + case EVENT_ATTENDEE_CHAIR_ROLE: + attendeePtr->setRole(EventAttendee::CHAIR_ROLE); + break; + default: + attendeePtr->setRole(EventAttendee::CHAIR_ROLE); + break; + } + + // load status + cal_event_attendee_status_type_t attendeeStatus = + static_cast(calendar_svc_struct_get_int( + m_platformEvent, + CAL_VALUE_INT_ATTENDEE_DETAIL_STATUS)); + if (0 > attendeeStatus) { + LogError("cannot read attendee status"); + return; + } + switch (attendeeStatus) { + case EVENT_ATTENDEE_PENDING_AT_STATUS: + attendeePtr->setStatus(EventAttendee::PENDING_AT_STATUS); + break; + case EVENT_ATTENDEE_ACCEPTED_AT_STATUS: + attendeePtr->setStatus(EventAttendee::ACCEPTED_AT_STATUS); + break; + case EVENT_ATTENDEE_DECLINED_AT_STATUS: + attendeePtr->setStatus(EventAttendee::DECLINED_AT_STATUS); + break; + case EVENT_ATTENDEE_TENTATIVE_AT_STATUS: + attendeePtr->setStatus(EventAttendee::TENTATIVE_AT_STATUS); + break; + case EVENT_ATTENDEE_DELEGATED_AT_STATUS: + attendeePtr->setStatus(EventAttendee::DELEGATED_AT_STATUS); + break; + case EVENT_ATTENDEE_COMPLETED_AT_STATUS: + attendeePtr->setStatus(EventAttendee::COMPLETED_AT_STATUS); + break; + case EVENT_ATTENDEE_IN_PROCESS_AT_STATUS: + attendeePtr->setStatus(EventAttendee::IN_PROCESS_AT_STATUS); + break; + default: + attendeePtr->setStatus(EventAttendee::PENDING_AT_STATUS); + break; + } + + // load RSVP + int attendeeRSVP = calendar_svc_value_get_int(attendee, CAL_VALUE_INT_ATTENDEE_RSVP); + if (0 > attendeeRSVP) { + LogError("cannot read attendee RSVP"); + return; + } + attendeePtr->setRSVP(attendeeRSVP>0 ? true : false); + + // load type + cal_event_attendee_type_t attendeeType = + static_cast(calendar_svc_struct_get_int( + m_platformEvent, + CAL_VALUE_INT_ATTENDEE_DETAIL_TYPE)); + if (0 > attendeeType) { + LogError("cannot read attendee type"); + return; + } + switch (attendeeType) { + case EVENT_ATTENDEE_INDIVIDUAL_TYPE: + attendeePtr->setType(EventAttendee::INDIVIDUAL_TYPE); + break; + case EVENT_ATTENDEE_GROUP_TYPE: + attendeePtr->setType(EventAttendee::GROUP_TYPE); + break; + case EVENT_ATTENDEE_RESOURCE_TYPE: + attendeePtr->setType(EventAttendee::RESOURCE_TYPE); + break; + case EVENT_ATTENDEE_ROOM_TYPE: + attendeePtr->setType(EventAttendee::ROOM_TYPE); + break; + case EVENT_ATTENDEE_UNKNOWN_TYPE: + attendeePtr->setType(EventAttendee::UNKNOWN_TYPE); + break; + default: + attendeePtr->setType(EventAttendee::INDIVIDUAL_TYPE); + break; + } + + // load group + char* attendeeGroup = calendar_svc_value_get_str(attendee, CAL_VALUE_TXT_ATTENDEE_GROUP); + if (NULL == attendeeGroup) { + LogError("cannot read attendee group"); + return; + } + attendeePtr->setGroup(attendeeGroup); + + // load delegatorURI + char* attendeeDelegatorURI = calendar_svc_value_get_str(attendee, CAL_VALUE_TXT_ATTENDEE_DELEGATOR_URI); + if (NULL == attendeeDelegatorURI) { + LogError("cannot read attendee delegatorURI"); + return; + } + attendeePtr->setDelegatorURI(attendeeDelegatorURI); + + // load delegateURI + char* attendeeDelegateURI = calendar_svc_value_get_str(attendee, CAL_VALUE_TXT_ATTENDEE_DELEGATE_URI); + if (NULL == attendeeDelegateURI) { + LogError("cannot read attendee delegateURI"); + return; + } + attendeePtr->setDelegateURI(attendeeDelegateURI); + + // load uid + char* attendeeUId = calendar_svc_value_get_str(attendee, CAL_VALUE_TXT_ATTENDEE_UID); + if (NULL == attendeeUId) { + LogError("cannot read attendee UId"); + return; + } + attendeePtr->setPersonId(attendeeUId); + + m_abstractEvent->getAttendees()->push_back(attendeePtr); + } +} + +void EventWrapper::setPositionFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + double value = calendar_svc_struct_get_double( + m_platformEvent, + CAL_VALUE_DBL_LATITUDE); + m_abstractEvent->setLatitude(value); + + value = calendar_svc_struct_get_double( + m_platformEvent, + CAL_VALUE_DBL_LONGITUDE); + m_abstractEvent->setLongitude(value); +} + +void EventWrapper::setPriorityFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + cal_priority_type_t priority = static_cast(calendar_svc_struct_get_int(m_platformEvent, + CAL_VALUE_INT_PRIORITY)); + switch (priority) { + case EVENT_PRIORITY_LOW: + m_abstractEvent->setPriority(CalendarEvent::LOW_PRIORITY); + break; + case EVENT_PRIORITY_NORMAL: + m_abstractEvent->setPriority(CalendarEvent::MEDIUM_PRIORITY); + break; + case EVENT_PRIORITY_HIGH: + m_abstractEvent->setPriority(CalendarEvent::HIGH_PRIORITY); + break; + default: + m_abstractEvent->setPriority(CalendarEvent::MEDIUM_PRIORITY); + break; + } +} + +void EventWrapper::setCreatedDateFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + std::time_t createdDate = 0; + +// calendar F/W not supported +// time_t createdDate = calendar_svc_struct_get_time(m_platformEvent, +// CAL_VALUE_GMT_CREATED_DATE_TIME, +// CAL_TZ_FLAG_GMT); + + m_abstractEvent->setCreatedDate(createdDate); +} + +void EventWrapper::setCompletedDateFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + std::time_t completedDate = 0; + +// calendar F/W not supported +// time_t completedDate = calendar_svc_struct_get_time(m_platformEvent, +// CAL_VALUE_GMT_COMPLETED_DATE_TIME, +// CAL_TZ_FLAG_GMT); + + m_abstractEvent->setCompletedDate(completedDate); +} + +void EventWrapper::setProgressFromPlatformEvent() +{ + if (!m_platformEvent) { + ThrowMsg(UnknownException, "Null platform pointer."); + } + + int progress = 0; + +// not supported +// progress = calendar_svc_struct_get_int(m_platformEvent, CAL_VALUE_INT_PROGRESS); + + m_abstractEvent->setProgress(progress); +} + +void EventWrapper::displayAbstractEvent() +{ + m_abstractEvent->display(); +} + +void EventWrapper::displayPlatformEvent() +{ + LogDebug("event id: " << calendar_svc_struct_get_int(m_platformEvent, + CAL_VALUE_INT_INDEX)); + LogDebug("event start time: " << calendar_svc_struct_get_time( + m_platformEvent, CAL_VALUE_GMT_START_DATE_TIME, + CAL_TZ_FLAG_GMT)); + LogDebug("event end time: " << calendar_svc_struct_get_time(m_platformEvent, + CAL_VALUE_GMT_END_DATE_TIME, + CAL_TZ_FLAG_GMT)); + LogDebug("event location: " << calendar_svc_struct_get_str(m_platformEvent, + CAL_VALUE_TXT_LOCATION)); + LogDebug("event summary: " << calendar_svc_struct_get_str(m_platformEvent, + CAL_VALUE_TXT_SUMMARY)); + LogDebug("event description: " << calendar_svc_struct_get_str( + m_platformEvent, CAL_VALUE_TXT_DESCRIPTION)); + + LogDebug("event isAllDay: " << calendar_svc_struct_get_int( + m_platformEvent, CAL_VALUE_INT_ALL_DAY_EVENT)); + LogDebug("event organizer: " << calendar_svc_struct_get_str(m_platformEvent, + CAL_VALUE_TXT_ORGANIZER_NAME)); + LogDebug("event lastModifiedDate: " << calendar_svc_struct_get_time( + m_platformEvent, CAL_VALUE_GMT_LAST_MODIFIED_TIME, + CAL_TZ_FLAG_GMT)); + LogDebug("event visibility: " << calendar_svc_struct_get_int( + m_platformEvent, CAL_VALUE_INT_SENSITIVITY)); + LogDebug("event availability: " << calendar_svc_struct_get_int( + m_platformEvent, CAL_VALUE_INT_BUSY_STATUS)); + LogDebug("event alarmType: " << calendar_svc_struct_get_int( + m_platformEvent, CAL_VALUE_INT_ALARM_TYPE)); + LogDebug("event alarm time: " << calendar_svc_struct_get_time( + m_platformEvent, CAL_VALUE_GMT_ALARM_TIME, + CAL_TZ_FLAG_GMT)); + + GList *categoryList = NULL; + if (CAL_SUCCESS != calendar_svc_struct_get_list(m_platformEvent, + CAL_VALUE_LST_MEETING_CATEGORY, + &categoryList)) { + LogError("cannot read category list"); + return; + } + cal_value* category = NULL; + for (; categoryList; categoryList = g_list_next(categoryList)) { + category = static_cast(categoryList->data); + char* categoryName = calendar_svc_value_get_str(category, "category_name"); + if (NULL == categoryName) { + LogError("cannot read category name"); + return; + } + LogDebug("event categories: " << categoryName); + } + + LogDebug("event uid: " << calendar_svc_struct_get_str(m_platformEvent, + CAL_VALUE_TXT_UID)); + LogDebug("event recurrenceId: " << calendar_svc_struct_get_time( + m_platformEvent, CAL_VALUE_GMT_START_DATE_TIME, CAL_TZ_FLAG_GMT)); + + GList *attendees = NULL; + if (CAL_SUCCESS != calendar_svc_struct_get_list(m_platformEvent, + CAL_VALUE_LST_ATTENDEE_LIST, + &attendees)) { + LogError("cannot read attendee list"); + return; + } + cal_value* attendee = NULL; + for (; attendees; attendees = g_list_next(attendees)) { + attendee = static_cast(attendees->data); + char* attendeeName = calendar_svc_value_get_str(attendee, CAL_VALUE_TXT_ATTENDEE_DETAIL_NAME); + if (NULL == attendeeName) { + LogError("cannot read attendee name"); + return; + } + LogDebug("event attendees: " << attendeeName); + } + + LogDebug("event repeat frequency: " << calendar_svc_struct_get_int( + m_platformEvent, CAL_VALUE_INT_REPEAT_TERM)); + LogDebug("event repeat occurrence count: " << calendar_svc_struct_get_int( + m_platformEvent, CAL_VALUE_INT_REPEAT_OCCURRENCES)); + LogDebug("event repeat occurrence end date: " << calendar_svc_struct_get_time( + m_platformEvent, CAL_VALUE_GMT_REPEAT_END_DATE, + CAL_TZ_FLAG_GMT)); +} + +Api::Calendar::CalendarEvent::CalendarType EventWrapper::getType() +{ + return m_calendarType; +} + +} +} +} diff --git a/src/platform/Tizen/Calendar/EventWrapper.h b/src/platform/Tizen/Calendar/EventWrapper.h new file mode 100755 index 0000000..a3b7cd7 --- /dev/null +++ b/src/platform/Tizen/Calendar/EventWrapper.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _EVENT_WRAPPER_H_ +#define _EVENT_WRAPPER_H_ + +#include +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Calendar { + +class EventWrapper +{ + public: + EventWrapper(Api::Calendar::CalendarEvent::CalendarType type = Api::Calendar::CalendarEvent::EVENT_TYPE); + explicit EventWrapper(const Api::Calendar::CalendarEventPtr &event, Api::Calendar::CalendarEvent::CalendarType type = Api::Calendar::CalendarEvent::EVENT_TYPE); + explicit EventWrapper(cal_struct *event, Api::Calendar::CalendarEvent::CalendarType type = Api::Calendar::CalendarEvent::EVENT_TYPE); + virtual ~EventWrapper(); + cal_struct *convertAbstractEventToPlatformEvent(); + Api::Calendar::CalendarEventPtr convertPlatformEventToAbstractEvent(); + cal_struct* getPlatformEvent() const; + Api::Calendar::CalendarEventPtr getAbstractEvent() const; + void freePlatformEvent(); + void saveEvent(); + void loadEvent(int id); + void deleteEvent(); + void createEventFromString(std::string value); + std::string exportEventToString(); + + protected: + int getIDFromPlatformEvent() const; + void setDescriptionToPlatformEvent(); + void setSummaryToPlatformEvent(); + void setStartTimeToPlatformEvent(); + void setEndTimeToPlatformEvent(); + void setLocationToPlatformEvent(); + void setRecurrenceRuleToPlatformEvent(); + void setAlarmsToPlatformEvent(); + void setStatusToPlatformEvent(); + void setCategoriesToPlatformEvent(); + void setIDToPlatformEvent(); + void setIsAllDayToPlatformEvent(); + void setOrganizerToPlatformEvent(); + void setLastModifiedDateToPlatformEvent(); + void setVisibilityToPlatformEvent(); + void setAvailabilityToPlatformEvent(); + void setUIdToPlatformEvent(); + void setAttendeesToPlatformEvent(); + void setPositionToPlatformEvent(); + void setPriorityToPlatformEvent(); + void setCreatedDateToPlatformEvent(); + void setCompletedDateToPlatformEvent(); + void setProgressToPlatformEvent(); + + void setDescriptionFromPlatformEvent(); + void setSummaryFromPlatformEvent(); + void setStartTimeFromPlatformEvent(); + void setEndTimeFromPlatformEvent(); + void setLocationFromPlatformEvent(); + void setRecurrenceRuleFromPlatformEvent(); + void setAlarmsFromPlatformEvent(); + void setStatusFromPlatformEvent(); + void setCategoriesFromPlatformEvent(); + void setIDFromPlatformEvent(); + void setIsAllDayFromPlatformEvent(); + void setOrganizerFromPlatformEvent(); + void setLastModifiedDateFromPlatformEvent(); + void setVisibilityFromPlatformEvent(); + void setAvailabilityFromPlatformEvent(); + void setUIdFromPlatformEvent(); + void setRecurrenceIdFromPlatformEvent(); + void setAttendeesFromPlatformEvent(); + void setPositionFromPlatformEvent(); + void setPriorityFromPlatformEvent(); + void setCreatedDateFromPlatformEvent(); + void setCompletedDateFromPlatformEvent(); + void setProgressFromPlatformEvent(); + + private: + void displayAbstractEvent(); //only for debugging + void displayPlatformEvent(); //only for debugging + Api::Calendar::CalendarEvent::CalendarType getType(); + + cal_struct *m_platformEvent; + Api::Calendar::CalendarEventPtr m_abstractEvent; + Api::Calendar::CalendarEvent::CalendarType m_calendarType; +}; + +typedef DPL::SharedPtr EventWrapperPtr; + +} +} +} +#endif /* _EVENT_WRAPPER_H_ */ diff --git a/src/platform/Tizen/Calendar/config.cmake b/src/platform/Tizen/Calendar/config.cmake new file mode 100755 index 0000000..78e5686 --- /dev/null +++ b/src/platform/Tizen/Calendar/config.cmake @@ -0,0 +1,25 @@ +get_current_path() + +pkg_search_module(calendar REQUIRED calendar-service) +pkg_search_module(glib REQUIRED glib-2.0) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_CALENDAR + ${calendar_INCLUDE_DIRS} + ${glib_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_CALENDAR + ${calendar_LIBRARIES} + ${glib_LIBRARIES} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_CALENDAR + ${CURRENT_PATH}/Calendar.cpp + ${CURRENT_PATH}/CalendarManager.cpp + ${CURRENT_PATH}/EventWrapper.cpp + ${CURRENT_PATH}/CalendarFilter.cpp + ${CURRENT_PATH}/CalendarQuery.c + PARENT_SCOPE +) diff --git a/src/platform/Tizen/Call/CallHistory.cpp b/src/platform/Tizen/Call/CallHistory.cpp new file mode 100755 index 0000000..d51efd1 --- /dev/null +++ b/src/platform/Tizen/Call/CallHistory.cpp @@ -0,0 +1,322 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "CallHistory.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "CallHistoryFilter.h" + +using namespace TizenApis::Api::Tizen; +using namespace TizenApis::Api::Call; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace DPL; + +namespace TizenApis { +namespace Platform { +namespace Call { + +CallHistory::CallHistory() +{ + _db_init(); + + if (calllog_connect() == CALLLOG_ERROR_NONE) { + LogDebug("Successful to connect Call history DB "); + } else { + LogDebug("Failed to connect Call history DB "); + } +} + +CallHistory::~CallHistory() +{ + _db_finish(); + + if (calllog_disconnect() == CALLLOG_ERROR_NONE) { + LogDebug("Successful to disconnect Call history DB "); + } else { + LogDebug("Failed to disconnect Call history DB "); + } +} + +bool CallHistory::convertCallHistory(callhistory_query_s *query_log, CallHistoryEntryListPtr &callEntries) +{ + if (query_log == NULL || callEntries == NULL) + return false; + + CallHistoryEntryPropertiesPtr callHistoryItem(new CallHistoryEntryProperties()); + + std::string callType(""); + std::string direction(""); + std::string number(""); + + if (query_log->phone_number != NULL) { + number.append(query_log->phone_number); + } + + switch(query_log->calllog_type) { + case CALLLOG_TYPE_VOICE_ANSWERED: + callType.append("tel"); + direction.append("received"); + break; + case CALLLOG_TYPE_VOICE_OUTGOING: + callType.append("tel"); + direction.append("dialed"); + break; + case CALLLOG_TYPE_VOICE_MISSED_CHECKED: + callType.append("tel"); + direction.append("missed"); + break; + case CALLLOG_TYPE_VOICE_MISSED_UNCHECKED: + callType.append("tel"); + direction.append("missed-new"); + break; + case CALLLOG_TYPE_VOICE_REJECTED: + callType.append("tel"); + direction.append("rejected"); + break; + case CALLLOG_TYPE_VOICE_BLOCKED: + callType.append("tel"); + direction.append("blocked"); + break; + case CALLLOG_TYPE_VIDEO_ANSWERED: + callType.append("vt"); + direction.append("received"); + break; + case CALLLOG_TYPE_VIDEO_OUTGOING: + callType.append("vt"); + direction.append("dialed"); + break; + case CALLLOG_TYPE_VIDEO_MISSED_CHECKED: + callType.append("vt"); + direction.append("missed"); + break; + case CALLLOG_TYPE_VIDEO_MISSED_UNCHECKED: + callType.append("vt"); + direction.append("missed-new"); + break; + case CALLLOG_TYPE_VIDEO_REJECTED: + callType.append("vt"); + direction.append("rejected"); + break; + case CALLLOG_TYPE_VIDEO_BLOCKED: + callType.append("vt"); + direction.append("blocked"); + break; + default: + return false; + } + + std::stringstream contactId; + contactId << query_log->contact_db_id; + + callHistoryItem->setEntryId(query_log->calllog_db_id); + callHistoryItem->setCallType(callType); + callHistoryItem->setRemoteParty(number); + callHistoryItem->setContactId(contactId.str()); + callHistoryItem->setStartTime(query_log->timestamp); + callHistoryItem->setDuration((unsigned long)(query_log->duration_sec)); + callHistoryItem->setDirection(direction); + + callEntries->insert(callEntries->end(), callHistoryItem); + + return true; +} + +void CallHistory::find(const EventFindCallHistoryPtr& event) +{ + EventRequestReceiver::PostRequest(event); +} + +bool CallHistory::remove(const unsigned long entryId) +{ + try { + int ret = calllog_delete_from_db(entryId); + + if (ret == CALLLOG_ERROR_NONE) { + return true; + } else { + return false; + } + } catch (const Commons::PlatformException& ex) { + ThrowMsg(Commons::PlatformException, ex.GetMessage()); + } +} + +void CallHistory::removeBatch(const EventRemoveBatchPtr& event) +{ + EventRequestReceiver::PostRequest(event); +} + +bool CallHistory::executeQuery(std::string &query, CallHistoryEntryListPtr &callEntries) +{ + callhistory_query_s query_data; + + stmt hstmt = NULL; + int ret = 0; + + hstmt = _query_prepare((char *)(query.c_str())); + + do { + ret = _query_step(hstmt); + if (ret == SQLITE_ROW) { + query_data.calllog_db_id = (unsigned long)_query_column_int64(hstmt, 0); + query_data.calllog_type = (calllog_type_e)_query_column_int(hstmt, 1); + query_data.contact_db_id = _query_column_int(hstmt, 2); + query_data.phone_number = _query_column_text(hstmt, 3); + query_data.timestamp = (time_t)_query_column_int(hstmt, 4); + query_data.duration_sec = _query_column_int(hstmt, 5); + + convertCallHistory(&query_data, callEntries); + } else if (ret == SQLITE_DONE) { + break; + } else { + break; + } + } while (1); + + _query_finalize(hstmt); + return true; +} + +std::string CallHistory::convertAttrName(std::string &name) +{ + std::string attrName(""); + if (name.compare("remoteParty") == 0) { + return attrName.append("number"); + } else if (name.compare("startTime") == 0) { + return attrName.append("log_time"); + } else if (name.compare("duration") == 0) { + return attrName.append("data1"); + } else if (name.compare("direction") == 0) { + return attrName.append("log_type"); + } else { + return attrName; + } +} + +std::string CallHistory::makeQuerySortMode(SortModeArrayPtr attr) +{ + std::string query(""); + std::string attriName; + int cnt = 0; + SortModeArray::iterator it = attr->begin(); + + + for (;it!=attr->end(); ++it) { + attriName = (*it)->getAttributeName(); + attriName = convertAttrName(attriName); + if (attriName.compare("") != 0) { + if (cnt == 0) { + query.append(" ORDER BY "); + } else { + query.append(", "); + } + query.append(attriName); + + if ((*it)->getOrder() == Api::Tizen::ASCENDING_SORT_ORDER) { + query.append(" ASC"); + } else { + query.append(" DESC"); + } + cnt++; + } + } + + return query; +} + +void CallHistory::OnRequestReceived(const EventFindCallHistoryPtr& event) +{ + try { + CallHistoryEntryListPtr callHistoryListPtr(new CallHistoryEntryList()); + + std::string query ("SELECT id, log_type, contact_id, number, log_time, data1 FROM phonelogs"); + + CallHistoryFilterPtr filtering(new CallHistoryFilter()); + IFilterVisitorPtr filterTraversal = DPL::StaticPointerCast(filtering); + + if (event->getFilterIsSet()) { + FilterPtr filter = event->getFilter(); + filter->travel(filterTraversal, 0); + query.append(filtering->getResult()); + query.append(" AND log_type <= 12"); + } else { + query.append(" WHERE log_type <= 12"); + } + + if (event->getSortModesIsSet()) { + query.append(makeQuerySortMode(event->getSortMode())); + } else { + query.append(" ORDER BY log_time DESC"); + } + + if (event->getLimitIsSet()) { + query.append(" LIMIT "); + std::stringstream limitStream; + limitStream << event->getLimit(); + query.append(limitStream.str()); + if (event->getOffsetIsSet()) { + query.append(" OFFSET "); + std::stringstream offsetStream; + offsetStream << event->getOffset(); + query.append(offsetStream.str()); + } + } + + LogDebug("execute query [" << query << "]"); + + executeQuery(query, callHistoryListPtr); + event->setResult(callHistoryListPtr); + + } catch (const Commons::PlatformException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } +} + +void CallHistory::OnRequestReceived(const EventRemoveBatchPtr& event) +{ + try { + std::vector entryIds = event->getEntryIds(); + unsigned int cnt = 0; + int ret = CALLLOG_ERROR_NONE; + for (cnt = 0; cnt < entryIds.size(); cnt++) { + ret = calllog_delete_from_db(static_cast(entryIds[cnt])); + if (ret != CALLLOG_ERROR_NONE) { + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + } + } catch (const Commons::PlatformException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } +} + +} +} +} + diff --git a/src/platform/Tizen/Call/CallHistory.h b/src/platform/Tizen/Call/CallHistory.h new file mode 100755 index 0000000..9a7b988 --- /dev/null +++ b/src/platform/Tizen/Call/CallHistory.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_PLATFORM_CALLHISTORY_H_ +#define TIZENAPIS_PLATFORM_CALLHISTORY_H_ + +#include +#include + +#include +#include +#include +#include +#include +#include "CallHistoryQuery.h" + +namespace TizenApis { +namespace Platform { +namespace Call { + +class CallHistory : public Api::Call::ICallHistory +{ +public: + CallHistory(); + ~CallHistory(); + + void find(const Api::Call::EventFindCallHistoryPtr& event); + bool remove(const unsigned long entryId); + void removeBatch(const Api::Call::EventRemoveBatchPtr& event); + +private: + bool convertCallHistory(callhistory_query_s *query_log, Api::Call::CallHistoryEntryListPtr &callEntries); + bool executeQuery(std::string &query, Api::Call::CallHistoryEntryListPtr &callEntries); + std::string convertAttrName(std::string &name); + std::string makeQuerySortMode(Api::Tizen::SortModeArrayPtr attr); + +protected: + void OnRequestReceived(const Api::Call::EventFindCallHistoryPtr& event); + void OnRequestReceived(const Api::Call::EventRemoveBatchPtr& event); +}; + +} +} +} + +#endif diff --git a/src/platform/Tizen/Call/CallHistoryFilter.cpp b/src/platform/Tizen/Call/CallHistoryFilter.cpp new file mode 100755 index 0000000..49766e0 --- /dev/null +++ b/src/platform/Tizen/Call/CallHistoryFilter.cpp @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include + +#include "CallHistoryFilter.h" +#include "CallHistoryQuery.h" + +using namespace std; +using namespace TizenApis::Api::Tizen; +using namespace TizenApis::Api::Call; + +namespace { +const std::string STR_LOG_TYPE ("log_type"); +const std::string STR_CONTACT_ID ("contact_id"); +const std::string STR_NUMBER ("number"); +const std::string STR_LOG_TIME ("log_time"); +const std::string STR_DURATION ("data1"); +const std::string STR_VOICE_ANSWERED ("1"); +const std::string STR_VOICE_OUTGOING ("2"); +const std::string STR_VOICE_MISSED_UNCHECKED ("5"); +const std::string STR_VOICE_MISSED_CHECKED ("6"); +const std::string STR_VOICE_REJECTED ("9"); +const std::string STR_VOICE_BLOCKED ("11"); +const std::string STR_VIDEO_ANSWERED ("3"); +const std::string STR_VIDEO_OUTGOING ("4"); +const std::string STR_VIDEO_MISSED_UNCHECKED ("7"); +const std::string STR_VIDEO_MISSED_CHECKED ("8"); +const std::string STR_VIDEO_REJECTED ("10"); +const std::string STR_VIDEO_BLOCKED ("12"); +const std::string STR_LEFT_BRACKET(" ("); +const std::string STR_RIGHT_BRACKET(")"); +const std::string STR_AND(" AND "); +const std::string STR_OR(" OR "); +const std::string STR_GREATER_THAN (">"); +const std::string STR_LESS_THAN ("<"); +const std::string STR_EQUAL ("="); +const std::string STR_S_QUOTATION ("'"); +} +namespace TizenApis { +namespace Platform { +namespace Call { + +CallHistoryFilter::CallHistoryFilter() : m_query("") +{ + init(); +} + +CallHistoryFilter::~CallHistoryFilter() +{ +} + +void CallHistoryFilter::visitPreComposite(FilterType& type, int depth) +{ + m_query = m_query + STR_LEFT_BRACKET; +} + +void CallHistoryFilter::visitInComposite(FilterType& type, int depth) +{ + if(type == Api::Tizen::UNION_FILTER) + m_query = m_query + STR_OR; + else if(type == Api::Tizen::INTERSECTION_FILTER) + m_query = m_query + STR_AND; +} + +void CallHistoryFilter::visitPostComposite(FilterType& type, int depth) +{ + m_query = m_query + STR_RIGHT_BRACKET; +} + +void CallHistoryFilter::visitAttribute(std::string& attrName, Api::Tizen::AnyArrayPtr& values, std::string& matchFlag, bool caseSensitive, int depth) +{ + std::string str (""); + + if (values == NULL) { + return; + } + + if (values->size() == 1) { + AnyPtr value = values->at(0); + str.append(convertAttribute(attrName, value)); + } else if (values->size() > 1) { + str.append(convertAttributeArray(attrName, values)); + } + + m_query = m_query + str; +} + +void CallHistoryFilter::visitAttributeRange(std::string& attrName, AnyPtr& initialValue, AnyPtr& endValue, int depth) +{ + string str (""); + string name (""); + string initialValueStr (""); + string endValueStr (""); + + if (attrName.compare("remoteParty") == 0) { + name = STR_NUMBER; + } else if (attrName.compare("contactId") == 0) { + name = STR_CONTACT_ID; + } else if (attrName.compare("startTime") == 0) { + name = STR_LOG_TIME; + } else if (attrName.compare("duration") == 0) { + name = STR_DURATION; + } else { + name = attrName; + } + + if (initialValue != NULL) { + if(initialValue->getType() == PrimitiveType_Time) { + tm date = DPL::DynamicPointerCast< Any_T >(initialValue)->getValue(); + std::stringstream time; + time << mktime(&date); + initialValueStr = time.str(); + } else { + initialValueStr = initialValue->toString(); + } + } + + if (endValue != NULL) { + if(endValue->getType() == PrimitiveType_Time) { + tm date = DPL::DynamicPointerCast< Any_T >(endValue)->getValue(); + std::stringstream time; + time << mktime(&date); + endValueStr = time.str(); + + } else { + endValueStr = endValue->toString(); + } + } + + if (initialValue != NULL && endValue == NULL) { + str = STR_LEFT_BRACKET + name + STR_GREATER_THAN + STR_EQUAL + STR_S_QUOTATION + initialValueStr + STR_S_QUOTATION + STR_RIGHT_BRACKET; + } else if (initialValue == NULL && endValue != NULL) { + str = STR_LEFT_BRACKET + name + STR_LESS_THAN + STR_S_QUOTATION + endValueStr + STR_S_QUOTATION + STR_RIGHT_BRACKET; + } else if (initialValue != NULL && endValue != NULL) { + str = STR_LEFT_BRACKET + name + STR_GREATER_THAN + STR_EQUAL + STR_S_QUOTATION + initialValueStr + STR_S_QUOTATION + STR_AND + name + STR_LESS_THAN + STR_S_QUOTATION + endValueStr + STR_S_QUOTATION + STR_RIGHT_BRACKET; + } + + m_query = m_query + str; +} + +void CallHistoryFilter::init() +{ + m_query.clear(); + m_query.append(" WHERE"); +} +std::string CallHistoryFilter::convertAttributeArray(std::string &name, AnyArrayPtr& values) +{ + std::string query(""); + AnyArray::iterator it = values->begin(); + query.append(STR_LEFT_BRACKET); + + do { + if (it != values->begin()) { + query.append(STR_OR); + } + query.append(convertAttribute(name, *it)); + it++; + } while(it != values->end()); + + query.append(STR_RIGHT_BRACKET); + return query; +} + +std::string CallHistoryFilter::convertAttribute(std::string &name, AnyPtr& value) +{ + std::string query(""); + if (name.compare("direction") == 0) { + if (value->toString().compare("received") == 0) { + query = STR_LEFT_BRACKET + STR_LOG_TYPE + STR_EQUAL + STR_VOICE_ANSWERED + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VIDEO_ANSWERED + STR_RIGHT_BRACKET; + } else if (value->toString().compare("dialed") == 0) { + query = STR_LEFT_BRACKET + STR_LOG_TYPE + STR_EQUAL + STR_VOICE_OUTGOING + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VIDEO_OUTGOING + STR_RIGHT_BRACKET; + } else if (value->toString().compare("missed") == 0) { + query = STR_LEFT_BRACKET + STR_LOG_TYPE + STR_EQUAL + STR_VOICE_MISSED_CHECKED + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VIDEO_MISSED_CHECKED + STR_RIGHT_BRACKET; + } else if (value->toString().compare("missed-new") == 0) { + query = STR_LEFT_BRACKET + STR_LOG_TYPE + STR_EQUAL + STR_VOICE_MISSED_UNCHECKED + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VIDEO_MISSED_UNCHECKED + STR_RIGHT_BRACKET; + } else if (value->toString().compare("rejected") == 0) { + query = STR_LEFT_BRACKET + STR_LOG_TYPE + STR_EQUAL + STR_VOICE_REJECTED + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VIDEO_REJECTED + STR_RIGHT_BRACKET; + } else if (value->toString().compare("blocked") == 0) { + query = STR_LEFT_BRACKET + STR_LOG_TYPE + STR_EQUAL + STR_VOICE_BLOCKED + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VIDEO_BLOCKED + STR_RIGHT_BRACKET; + } else { + query = STR_LEFT_BRACKET + STR_LOG_TYPE + "=0" + STR_RIGHT_BRACKET; + } + } else if (name.compare("callType") == 0) { + if (value->toString().compare("tel") == 0) { + query = STR_LEFT_BRACKET + STR_LOG_TYPE + STR_EQUAL + STR_VOICE_ANSWERED + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VOICE_OUTGOING + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VOICE_MISSED_UNCHECKED + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VOICE_MISSED_CHECKED + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VOICE_REJECTED + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VOICE_BLOCKED + STR_RIGHT_BRACKET; + } else if (value->toString().compare("vt") == 0) { + query = STR_LEFT_BRACKET + STR_LOG_TYPE + STR_EQUAL + STR_VIDEO_ANSWERED + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VIDEO_OUTGOING + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VIDEO_MISSED_UNCHECKED + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VIDEO_MISSED_CHECKED + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VIDEO_REJECTED + STR_OR + + STR_LOG_TYPE + STR_EQUAL + STR_VIDEO_BLOCKED + STR_RIGHT_BRACKET; + } else { + query = STR_LEFT_BRACKET + STR_LOG_TYPE + "=0" + STR_RIGHT_BRACKET; + } + } else if (name.compare("remoteParty") == 0) { + query = STR_LEFT_BRACKET + STR_NUMBER + STR_EQUAL + STR_S_QUOTATION + value->toString() + STR_S_QUOTATION + STR_RIGHT_BRACKET; + } else if (name.compare("contactId") == 0) { + query = STR_LEFT_BRACKET + STR_CONTACT_ID + STR_EQUAL + STR_S_QUOTATION + value->toString() + STR_S_QUOTATION + STR_RIGHT_BRACKET; + } else if (name.compare("startTime") == 0) { + std::string dateStr (""); + if(value->getType() == PrimitiveType_Time) { + tm date = DPL::DynamicPointerCast< Any_T >(value)->getValue(); + std::stringstream time; + time << mktime(&date); + dateStr = time.str(); + } else { + return query; + } + query = STR_LEFT_BRACKET + STR_LOG_TIME + STR_EQUAL + STR_S_QUOTATION + dateStr + STR_S_QUOTATION + STR_RIGHT_BRACKET; + } else if (name.compare("duration") == 0) { + query = STR_LEFT_BRACKET + STR_DURATION + STR_EQUAL + STR_S_QUOTATION + value->toString() + STR_S_QUOTATION + STR_RIGHT_BRACKET; + } + + return query; +} + +std::string CallHistoryFilter::getResult() const +{ + return m_query; +} + +} +} +} diff --git a/src/platform/Tizen/Call/CallHistoryFilter.h b/src/platform/Tizen/Call/CallHistoryFilter.h new file mode 100755 index 0000000..99e4f76 --- /dev/null +++ b/src/platform/Tizen/Call/CallHistoryFilter.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_PLATFORM_CALLHISTORY_FILTER_H_ +#define TIZENAPIS_PLATFORM_CALLHISTORY_FILTER_H_ + +#include +#include +#include "time.h" + +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Call { +class CallHistoryFilter: public Api::Tizen::IFilterVisitor +{ +private: + std::string m_query; +public: + CallHistoryFilter(); + ~CallHistoryFilter(); + + void visitPreComposite(Api::Tizen::FilterType& type, int depth); + + void visitInComposite(Api::Tizen::FilterType& type, int depth); + + void visitPostComposite(Api::Tizen::FilterType& type, int depth); + + void visitAttribute(std::string& attrName, + Api::Tizen::AnyArrayPtr& values, + std::string& matchFlag, + bool caseSensitive, + int depth); + + void visitAttributeRange(std::string& attrName, + Api::Tizen::AnyPtr& initialValue, + Api::Tizen::AnyPtr& endValue, + int depth); + + void init(); + std::string getResult() const; + std::string convertAttributeArray(std::string &name, Api::Tizen::AnyArrayPtr& values); + std::string convertAttribute(std::string &name, Api::Tizen::AnyPtr& value); +}; + +typedef DPL::SharedPtr CallHistoryFilterPtr; + +} +} +} +#endif \ No newline at end of file diff --git a/src/platform/Tizen/Call/CallHistoryQuery.c b/src/platform/Tizen/Call/CallHistoryQuery.c new file mode 100755 index 0000000..59901cd --- /dev/null +++ b/src/platform/Tizen/Call/CallHistoryQuery.c @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "CallHistoryQuery.h" +#include +#include + +sqlite3 *hDBCt; + +static int db_connnect_count = 0; + +query_error _db_init() +{ + int rc = 0; + query_error error_code = QUERY_SUCCESS; + + db_connnect_count++; + if(!hDBCt) + { + rc = db_util_open(QUERY_DB_PATH, &hDBCt, 0); + if(rc != SQLITE_OK) + error_code = QUERY_FAIL; + } + return error_code; +} + +query_error _db_finish() +{ + int rc = 0; + query_error error_code = QUERY_SUCCESS; + + db_connnect_count--; + if(db_connnect_count == 0) + { + rc = db_util_close(hDBCt); + if(rc != SQLITE_OK) + error_code = QUERY_FAIL; + else + hDBCt = NULL; + } + return error_code; +} + +query_error _exec_query(char* query) +{ + int rc = -1; + char* pszErrorMsg = NULL; + query_error error_code = QUERY_SUCCESS; + + rc = sqlite3_exec(hDBCt, query, NULL, NULL, &pszErrorMsg); + + if(SQLITE_OK != rc) + { + error_code = QUERY_FAIL; + } + + if(pszErrorMsg) + sqlite3_free(pszErrorMsg); + + return error_code; +} + +int _query_step(stmt pStmt) +{ + return sqlite3_step(pStmt); +} + +void _contact_query_finalize(stmt pStmt) +{ + int rc = -1; + + if(!pStmt) + return; + + rc = sqlite3_finalize(pStmt); + if(rc != SQLITE_OK) + { + } +} + +int _contact_query_column_int(stmt pStmt, int pos) +{ + return (int)sqlite3_column_int(pStmt, pos); +} + +char* _contact_query_column_text(stmt pStmt, int pos) +{ + return (char *)sqlite3_column_text(pStmt, pos); +} + +void _query_finalize(stmt pStmt) +{ + int rc = -1; + + if(!pStmt) + return; + + rc = sqlite3_finalize(pStmt); + if(rc != SQLITE_OK) + { + + } +} + +int _query_bind_double(stmt pStmt, int pos, double num) +{ + return sqlite3_bind_double(pStmt, pos, num); +} + +int _query_bind_int(stmt pStmt, int pos, int num) +{ + return sqlite3_bind_int(pStmt, pos, num); +} + +int _query_bind_text(stmt pStmt, int pos, char* str) +{ + int len = 0; + if(str != NULL) + { + len = strlen(str); + return sqlite3_bind_text(pStmt, pos, (const char*)str, len, SQLITE_STATIC); + } + return -1; +} + +void _query_stmt_reset(stmt stmt) +{ + sqlite3_reset(stmt); + sqlite3_clear_bindings(stmt); +} + +int _query_column_int(stmt pStmt, int pos) +{ + return sqlite3_column_int(pStmt, pos); +} + +long long int _query_column_int64(stmt pStmt, int pos) +{ + return sqlite3_column_int64(pStmt, pos); +} + +double _query_column_double(stmt pStmt, int pos) +{ + return sqlite3_column_double(pStmt, pos); +} + +char* _query_column_text(stmt pStmt, int pos) +{ + return (char *)sqlite3_column_text(pStmt, pos); +} + +stmt _query_prepare(char *query) +{ + int rc = -1; + stmt pStmt = NULL; + + printf("\nquery : %s !!!!\n", query); + + rc = sqlite3_prepare_v2(hDBCt, query, strlen(query), &pStmt, NULL); + + if(SQLITE_OK != rc) + { + return NULL; + } + + return pStmt; +} + diff --git a/src/platform/Tizen/Call/CallHistoryQuery.h b/src/platform/Tizen/Call/CallHistoryQuery.h new file mode 100755 index 0000000..2eef1cb --- /dev/null +++ b/src/platform/Tizen/Call/CallHistoryQuery.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef __QUERY_UTILITY_H__ +#define __QUERY_UTILITY_H__ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define QUERY_DB_PATH "/opt/dbspace/.contacts-svc.db" + +typedef sqlite3_stmt* stmt; + +typedef struct +{ + unsigned long calllog_db_id; + calllog_type_e calllog_type; + int contact_db_id; + char* phone_number; + time_t timestamp; + int duration_sec; +} callhistory_query_s; + +typedef enum +{ + QUERY_GROUP_CASE = -16, + QUERY_NORMALIZATION_ERROR = -15, + QUERY_SET_LIMIT = -14, + QUERY_NO_NEXT_ROW = -13, + QUERY_INSERT_FAIL = -12, + QUERY_ORDERING_FAIL = -11, + QUERY_STATEMENT_FAIL = -10, + QUERY_INVALID_ATTRIBUTE = -9, + QUERY_OVER_MAX_COUNT = -8, + QUERY_OVER_MAX_PROPERTY_CLASS = -7, + QUERY_NULL_PARAMETER = -6, + QUERY_NO_RECORD = -5, + QUERY_HANDLE_NONE, + QUERY_INVALID_TYPE, + QUERY_ALLOCATE_MEMORY_FAIL, + QUERY_FAIL = -1, + QUERY_SUCCESS = 0, +}query_error; + +clock_t _get_clock(); + +bool _print_time(clock_t begin, clock_t finish, const char* function_name); + +query_error _db_init(); + +query_error _db_finish(); + +query_error _exec_query(char* query); + +int _query_step(stmt pStmt); + +void _contact_query_finalize(stmt pStmt); + +int _contact_query_column_int(stmt pStmt, int pos); + +char* _contact_query_column_text(stmt pStmt, int pos); + +void _query_finalize(stmt pStmt); + +int _query_bind_int(stmt pStmt, int pos, int num); + +int _query_bind_double(stmt pStmt, int pos, double num); + +int _query_bind_text(stmt pStmt, int pos, char* str); + +void _query_stmt_reset(stmt stmt); + +int _query_column_int(stmt pStmt, int pos); + +long long int _query_column_int64(stmt pStmt, int pos); + +double _query_column_double(stmt pStmt, int pos); + +char* _query_column_text(stmt pStmt, int pos); + +stmt _query_prepare(char *query); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/src/platform/Tizen/Call/config.cmake b/src/platform/Tizen/Call/config.cmake new file mode 100755 index 0000000..44b9422 --- /dev/null +++ b/src/platform/Tizen/Call/config.cmake @@ -0,0 +1,29 @@ +get_current_path() +pkg_search_module(contacts-service REQUIRED contacts-service) +pkg_search_module(capicallhistory REQUIRED capi-social-call-log) +pkg_search_module(glib REQUIRED glib-2.0) +pkg_search_module(libpcrecpp REQUIRED libpcrecpp) + + +set(INCLUDES_PLATFORM_IMPLEMENTATION_CALL + ${contacts-service_INCLUDE_DIRS} + ${capicallhistory_INCLUDE_DIRS} + ${glib_INCLUDE_DIRS} + ${libpcrecpp_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_CALL + ${contacts-service_LIBRARIES} + ${capicallhistory_LIBRARIES} + ${glib_LIBRARIES} + ${libpcrecpp_LIBRARIES} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_CALL + ${CURRENT_PATH}/CallHistory.cpp + ${CURRENT_PATH}/CallHistoryFilter.cpp + ${CURRENT_PATH}/CallHistoryQuery.c + PARENT_SCOPE +) diff --git a/src/platform/Tizen/Contact/AddressBook.cpp b/src/platform/Tizen/Contact/AddressBook.cpp new file mode 100755 index 0000000..878275a --- /dev/null +++ b/src/platform/Tizen/Contact/AddressBook.cpp @@ -0,0 +1,792 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file AddressBook.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "AddressBook.h" +#include "ContactWrapper.h" +#include "ContactSearchEngine.h" +#include "ContactFilterValidator.h" + +namespace TizenApis { +namespace Platform { +namespace Contact { + +using namespace TizenApis::Api::Contact; +using namespace TizenApis::Api::Tizen; +using namespace WrtDeviceApis::Commons; +using namespace std; + +using TizenApis::Api::Contact::Contact; + +AddressBook::AddressBook(IAddressBook::AddressBookType changeType) : + IAddressBook(changeType), + m_name("TEST_ADDRESS_BOOK") +{ + LogDebug("entered"); + setDaClientIdByDaInit(); +} + +AddressBook::~AddressBook() +{ +} + +ContactPropertiesPtr AddressBook::convertFromString(const string &vObjectStr, const string &format) +{ + const void *vcard_stream = vObjectStr.c_str(); + CTSstruct* cts; + + if(format != "VCARD_30") + ThrowMsg(UnsupportedException, "Only support vCard 3.0."); + + int ret = contacts_svc_get_contact_from_vcard(vcard_stream, &cts); + if(CTS_SUCCESS != ret) + ThrowMsg(PlatformException, "Fail to convert contact from vCard."); + + ContactWrapperPtr contactWrapper(new ContactWrapper(m_bookType)); + Try { + contactWrapper->setPlatformContact(cts); + } Catch (PlatformException) { + ThrowMsg(PlatformException, "Fail to extract contact from platform object."); + } + + return DPL::StaticPointerCast(contactWrapper->getAbstractContact()); +} + +string AddressBook::convertToString(const ContactPtr &contact, const string &format) +{ + char *vcard_stream = NULL; + + if(format != "VCARD_30") + ThrowMsg(UnsupportedException, "Only support vCard 3.0."); + + ContactWrapperPtr contactWrapper(new ContactWrapper(m_bookType)); + Try { + contactWrapper->setAbstractContact(contact, true); + } Catch (PlatformException) { + ThrowMsg(PlatformException, "Fail to extract contact to platform object."); + } + int ret = contacts_svc_get_vcard_from_contact(contactWrapper->getPlatformContact(), &vcard_stream); + if(ret != CTS_SUCCESS) + ThrowMsg(PlatformException, "Fail to convert to vCard."); + + string result((char *)vcard_stream); + + free(vcard_stream); + + return result; +} + +ContactPtr AddressBook::add(const ContactPropertiesPtr &contactProperties) +{ + ContactPtr contact(new Contact(*contactProperties)); + + if(!contact) + ThrowMsg(InvalidArgumentException, "ContactProperties argument is wrong"); + + internalAddContact(contact); + m_latestVersion = get_contact_version(); + + return contact; +} + +void AddressBook::update(const ContactPtr &contact) +{ + if(!contact) + ThrowMsg(InvalidArgumentException, "Contact argument is wrong"); + + internalAddContact(contact); + m_latestVersion = get_contact_version(); +} + +void AddressBook::remove(const string &id) +{ + int contactId; + + try { + istringstream iss(id); + iss >> contactId; + } catch (...) { + ThrowMsg(InvalidArgumentException, "Id changeType is wrong."); + } + + Try { + internalDeleteContactById(contactId); + } Catch (NotFoundException) { + LogError("Contact (id:" << contactId << ") does not exist."); + ThrowMsg(NotFoundException, "Contact (id:" << contactId << ") does not exist."); + } Catch (PlatformException) { + LogError("Error during deleting contact. " << _rethrown_exception.GetMessage()); + ThrowMsg(PlatformException, "Error during deleting contact."); + } + m_latestVersion = get_contact_version(); +} + +long AddressBook::addChangeListener(const EventAddressBookChangeListenerEmitterPtr &emitter) +{ + DPL::Mutex::ScopedLock lock(&m_addressBookEmittersMutex); + + if(m_addressBookEmitters.size() == 0) + { + m_latestVersion = get_contact_version(); + contacts_svc_subscribe_change(CTS_SUBSCRIBE_CONTACT_CHANGE, + contactsSvcContactChangedCallback, reinterpret_cast(this)); + contacts_svc_subscribe_change(CTS_SUBSCRIBE_ADDRESSBOOK_CHANGE, + refresh_addressbook_list, reinterpret_cast(this)); + } + + m_addressBookEmitters.attach(emitter); + + return static_cast(emitter->getId()); +} + +void AddressBook::removeChangeListener(const long watchId) +{ + DPL::Mutex::ScopedLock lock(&m_addressBookEmittersMutex); + m_addressBookEmitters.detach(watchId); + + if(m_addressBookEmitters.size() == 0) + { + m_latestVersion = 0; + contacts_svc_unsubscribe_change(CTS_SUBSCRIBE_CONTACT_CHANGE, + contactsSvcContactChangedCallback); + contacts_svc_unsubscribe_change(CTS_SUBSCRIBE_ADDRESSBOOK_CHANGE, + refresh_addressbook_list); + } +} + +void AddressBook::OnRequestReceived(const EventAddressBookAddBatchPtr &event) +{ + LogDebug("entered"); + + ContactPropertiesArrayPtr contactProperties(NULL); + Try { + if(!event->getContactPropertiesIsSet()) + ThrowMsg(InvalidArgumentException, "Contacts were not set."); + + contactProperties = event->getContactProperties(); + if(!contactProperties) + ThrowMsg(InvalidArgumentException, "No contacts."); + + } Catch(InvalidArgumentException) { + LogError("Invalid arguments for adding contacts : " << _rethrown_exception.GetMessage()); + event->setResult(false); + event->setExceptionCode(ExceptionCodes::InvalidArgumentException); + return; + } + + Try + { + ContactArrayPtr contacts(new ContactArray()); + int ret = contacts_svc_begin_trans(); + if (ret < 0) { + LogError("error code " << ret); + ThrowMsg(PlatformException, "Error during executing contacts_svc_begin_trans()"); + } + + for(ContactPropertiesArray::iterator i = contactProperties->begin(); i != contactProperties->end(); i++) + { + ContactPtr contact(new Contact(*(*i))); + + internalAddContact(contact); + + contacts->push_back(contact); + } + contacts_svc_end_trans(true); + if (ret < 0) { + LogError("error code " << ret); + ThrowMsg(PlatformException, "Error during executing contacts_svc_end_trans()"); + } + event->setContacts(contacts); + } + Catch (NotFoundException) + { + contacts_svc_end_trans(false); + LogError("Contact doesn't exist : " << _rethrown_exception.GetMessage()); + event->setResult(false); + event->setExceptionCode(ExceptionCodes::NotFoundException); + return; + } + Catch (PlatformException) { + contacts_svc_end_trans(false); + LogError("Error during adding contact : " << _rethrown_exception.GetMessage()); + event->setResult(false); + event->setExceptionCode(ExceptionCodes::PlatformException); + return; + } + m_latestVersion = get_contact_version(); + + event->setResult(true); + event->setExceptionCode(ExceptionCodes::None); +} + +void AddressBook::OnRequestReceived(const EventAddressBookUpdateBatchPtr &event) +{ + LogDebug("entered"); + + ContactArrayPtr contacts(NULL); + + Try { + if(!event->getContactsIsSet()) + ThrowMsg(InvalidArgumentException, "Contacts were not set."); + + contacts = event->getContacts(); + if(!contacts) + ThrowMsg(InvalidArgumentException, "No contacts."); + + } Catch(InvalidArgumentException) { + LogError("Invalid arguments for updating contacts : " << _rethrown_exception.GetMessage()); + event->setResult(false); + event->setExceptionCode(ExceptionCodes::InvalidArgumentException); + return; + } + + Try + { + int ret = contacts_svc_begin_trans(); + if (ret < 0) { + LogError("error code " << ret); + ThrowMsg(PlatformException, "Error during executing contacts_svc_begin_trans()"); + } + + for(ContactArray::iterator i = contacts->begin(); i != contacts->end(); i++) + { + ContactPtr contact = *i; + + internalAddContact(contact); + } + contacts_svc_end_trans(true); + if (ret < 0) { + LogError("error code " << ret); + ThrowMsg(PlatformException, "Error during executing contacts_svc_end_trans()"); + } + } + Catch (NotFoundException) + { + contacts_svc_end_trans(false); + LogError("Contact doesn't exist : " << _rethrown_exception.GetMessage()); + event->setResult(false); + event->setExceptionCode(ExceptionCodes::NotFoundException); + return; + } + Catch (PlatformException) { + contacts_svc_end_trans(false); + LogError("Error during updating contact : " << _rethrown_exception.GetMessage()); + event->setResult(false); + event->setExceptionCode(ExceptionCodes::PlatformException); + return; + } + m_latestVersion = get_contact_version(); + + event->setResult(true); + event->setExceptionCode(ExceptionCodes::None); +} + + +void AddressBook::OnRequestReceived(const EventAddressBookRemoveBatchPtr &event) +{ + LogDebug("entered"); + + StringArrayPtr contactIds(NULL); + + Try { + if(!event->getContactIdsIsSet()) + ThrowMsg(InvalidArgumentException, "Contacts were not set."); + + contactIds = event->getContactIds(); + if(!contactIds) + ThrowMsg(InvalidArgumentException, "No contacts."); + + } Catch(InvalidArgumentException) { + LogError("Invalid arguments for updating contacts : " << _rethrown_exception.GetMessage()); + event->setResult(false); + event->setExceptionCode(ExceptionCodes::InvalidArgumentException); + return; + } + + Try + { + int ret = contacts_svc_begin_trans(); + if (ret < 0) { + LogError("error code " << ret); + ThrowMsg(PlatformException, "Error during executing contacts_svc_begin_trans()"); + } + for(StringArray::iterator i = contactIds->begin(); i != contactIds->end(); i++) + { + string contactIdStr = *i; + + int contactId; + + try { + istringstream iss(contactIdStr); + iss >> contactId; + } catch (...) { + ThrowMsg(InvalidArgumentException, "Id (" << contactIdStr << ") changeType is wrong."); + } + + internalDeleteContactById(contactId); + } + contacts_svc_end_trans(true); + if (ret < 0) { + LogError("error code " << ret); + ThrowMsg(PlatformException, "Error during executing contacts_svc_end_trans()"); + } + } + Catch (InvalidArgumentException) + { + contacts_svc_end_trans(false); + LogError("Invalid contact id : " << _rethrown_exception.GetMessage()); + event->setResult(false); + event->setExceptionCode(ExceptionCodes::InvalidArgumentException); + return; + } + Catch (NotFoundException) + { + contacts_svc_end_trans(false); + LogError("Contact doesn't exist : " << _rethrown_exception.GetMessage()); + event->setResult(false); + event->setExceptionCode(ExceptionCodes::NotFoundException); + return; + } + Catch (PlatformException) { + contacts_svc_end_trans(false); + LogError("Error during updating contact : " << _rethrown_exception.GetMessage()); + event->setResult(false); + event->setExceptionCode(ExceptionCodes::PlatformException); + return; + } + m_latestVersion = get_contact_version(); + + event->setResult(true); + event->setExceptionCode(ExceptionCodes::None); +} + +void AddressBook::OnRequestReceived(const EventAddressBookFindPtr &event) +{ + Try { + ContactSearchEnginePtr searchEngine(new ContactSearchEngine(ContactSearchEngine::CONTACT_QUERY)); + + if(event->getFilterIsSet()) + { + FilterPtr filter = event->getFilter(); + + // FIXME validator have to be placed at JS binding. + FilterValidatorPtr validator = ContactFilterValidatorFactory::getContactFilterValidator(); + bool success = filter->validate(validator); + + if(!success) + ThrowMsg(InvalidArgumentException, "Invalid filter arguments."); + + searchEngine->setCondition(filter); + } + + // Currently not support attributeOfInterests + //if (event->getAttributesOfInterestIsSet()) + // searchEngine->setAttributeOfInterest(event->getAttributesOfInterest()); + //else + // searchEngine->setAttributeOfInterest(); + + searchEngine->setAttributeOfInterest(); + + if (event->getSortModesIsSet()) + { + if(event->getSortModes()->size() > 0) + searchEngine->setSortMode(event->getSortModes()->at(0)); + else + searchEngine->setSortMode(); + } + else + searchEngine->setSortMode(); + + event->setContacts(searchEngine->getContactSearchResult()); + event->setResult(true); + + } Catch (NotFoundException) { + LogError("Contact doesn't exist : " << _rethrown_exception.GetMessage()); + event->setExceptionCode(ExceptionCodes::NotFoundException); + event->setResult(false); + + } Catch (PlatformException) { + LogError("Error during deleting contact : " << _rethrown_exception.GetMessage()); + event->setExceptionCode(ExceptionCodes::PlatformException); + event->setResult(false); + + } Catch (InvalidArgumentException) { + LogError("Invalid Arguments : " << _rethrown_exception.GetMessage()); + event->setExceptionCode(ExceptionCodes::InvalidArgumentException); + event->setResult(false); + } +} + +void AddressBook::daNotifyCallback(user_notify_info_t *notify_info, void *user_data) +{ + if (notify_info == NULL) + { + LogDebug("notify_info is NULL!!"); + return; + } + + if (notify_info->state == DA_STATE_FAILED || + notify_info->state == DA_STATE_CANCELED) + { + if (user_data != NULL) + { + DownImageInfo *downImageInfo; + downImageInfo = static_cast(user_data); + (downImageInfo->getWaitableEvent())->Signal(); + } + } +} + +void AddressBook::daGetDdInfoCallback(user_dd_info_t *dd_info, void *user_data) +{ + /* Empty CB */ +} + +void AddressBook::daUpdateDownloadInfoCallback(user_download_info_t *download_info, void *user_data) +{ + if(download_info == NULL) + { + LogDebug("download_info is NULL!!"); + return; + } + + if (user_data == NULL) + { + LogDebug("user_data is NULL!!"); + return; + } + + if (download_info->saved_path) + { + LogDebug("download_info->saved_path : " << download_info->saved_path); + + DownImageInfo *downImageInfo = static_cast(user_data); + string savedPath = download_info->saved_path; + downImageInfo->setDownloadedImagePath(savedPath); + (downImageInfo->getWaitableEvent())->Signal(); + } +} + +void AddressBook::setDaClientIdByDaInit(void) +{ + int da_ret = DA_INVALID_ID; + + da_client_cb_t da_cb = { 0 }; + + da_cb.user_noti_cb = &daNotifyCallback; + da_cb.send_dd_info_cb = &daGetDdInfoCallback; + da_cb.update_dl_info_cb = &daUpdateDownloadInfoCallback; + + da_ret = da_init(&da_cb, DA_NETWORK_MANAGING_METHOD_AUTO, &m_daClientId); + + if (da_ret != DA_RESULT_OK) + { + LogDebug("Error during da_init() da_ret: " << da_ret); + } +} + +void AddressBook::unsetDaClientIdByDaDeinit(void) +{ + da_deinit(m_daClientId); + + m_daClientId = DA_INVALID_ID; +} + +string AddressBook::downloadImage(const string &imgUrl) const +{ + LogDebug("URL : " << imgUrl); + + string result; + Try { + DownImageInfo downImageInfo; + int da_ret = DA_INVALID_ID; + int download_id = -1; + + DPL::WaitableEvent waitableEvent; + downImageInfo.setWaitableEvent(&waitableEvent); + da_ret = da_start_download_with_extension(m_daClientId, imgUrl.c_str(), + &download_id, DA_FEATURE_USER_DATA, + static_cast(&downImageInfo), NULL); + if (da_ret != DA_RESULT_OK) { + ThrowMsg(PlatformException, + "Error during da_start_download_with_extension() da_ret: " + << da_ret << ", m_daClientId: " << m_daClientId); + } + + DPL::WaitForSingleHandle(waitableEvent.GetHandle()); + waitableEvent.Reset(); + if ((downImageInfo.getDownloadedImagePath()).empty()) { + ThrowMsg(PlatformException, "Download failed"); + } + + result = downImageInfo.getDownloadedImagePath(); + + } Catch (Exception) { + LogError("Probably invalid URL(" << imgUrl << ") " << _rethrown_exception.GetMessage()); + } + + return result; +} + +string AddressBook::getRealPath(const string &path) const +{ + LogDebug("Path : " << path); + + string result; + Try + { + if ( validate("^(http(s)?://)?\\w+.*$", path, VALIDATE_MATCH_CASELESS) ) + { + // if path is URL then Image will be downloaded. + result = downloadImage(path); + } + else + { + result = path; + } + } + Catch(Exception) + { + //probably path doesn't exist + LogError("invalid path(" << path << ")"); + } + + return result; +} + +void AddressBook::internalAddContact(const ContactPtr &newContact) +{ + LogDebug("entered"); + + DPL::Mutex::ScopedLock lock(&m_contactEditingMutex); + + //translate provided path to real filesystem path + if (newContact->getPhotoURIIsSet()) + { + string realpath = getRealPath(newContact->getPhotoURI()); + newContact->setPhotoURI(realpath); + } + + ContactWrapperPtr contactWrapper(new ContactWrapper(m_bookType)); + contactWrapper->setAbstractContact(newContact, false); + CTSstruct* contact = contactWrapper->getPlatformContact(); + if (!contact) + { + LogError("Error during converting contact object"); + ThrowMsg(PlatformException, "Error during converting contact object"); + } + + if ( newContact->getIdIsSet() ) + { + int ret = contacts_svc_update_contact(contact); + if (ret == CTS_ERR_DB_RECORD_NOT_FOUND) + ThrowMsg(NotFoundException, "Error during executing contacts_svc_update_contact()"); + else if (ret < 0) { + LogError("error code " << ret); + ThrowMsg(PlatformException, "Error during executing contacts_svc_update_contact()"); + } + } + else + { + query_error error_code = QUERY_SUCCESS; + int addressBookId = 0; + int accountId = 0; + + string accountIdStr = newContact->getAccount()->getAccountId(); + try { + istringstream iss(accountIdStr); + iss >> accountId; + } catch (...) { + LogDebug("accountId changeType is wrong. (id:" << accountIdStr << ")"); + accountId = 0; + } + + addressBookId = find_addressbook_id(accountId, &error_code); + if(error_code != QUERY_SUCCESS) + addressBookId = 0; + + int id = contacts_svc_insert_contact(addressBookId, contact); + if (id < 0) { + LogError("error code " << id); + ThrowMsg(PlatformException, "Error during executing contacts_svc_insert_contact()"); + } + newContact->setId(id); + } +} + +void AddressBook::internalDeleteContactById(int id) +{ + LogDebug("entered with id " << id); + + if (id == -1) + return; + + DPL::Mutex::ScopedLock lock(&m_contactEditingMutex); + + int res = contacts_svc_delete_contact(id); + if (res == CTS_ERR_DB_RECORD_NOT_FOUND) + ThrowMsg(NotFoundException, "Error during executing contacts_svc_delete_contact()"); + else if (res != CTS_SUCCESS) + ThrowMsg(PlatformException, "Error during executing contacts_svc_delete_contact()"); +} + +void AddressBook::contactsSvcContactChangedCallback(void *data) +{ + AddressBook *addressBook = static_cast(data); + addressBook->contactsSvcContactChangedCallback(); +} + +void AddressBook::contactsSvcContactChangedCallback() +{ + if(m_addressBookEmitters.size() == 0) + return; + + CTSiter *iter; + int changeId = 0; + int changeType = 0; + int changeVersion = 0; + + bool contactInserted = false; + bool contactUpdated = false; + bool contactDeleted = false; + + int *addressBookIds = NULL; + int addressBookIdCount = 0; + + addressBookIds = get_all_addressbook_id(&addressBookIdCount); + + EventInfoAddressBookChangeAddedPtr contactsAdded(new EventInfoAddressBookChangeAdded()); + EventInfoAddressBookChangeUpdatedPtr contactsUpdated(new EventInfoAddressBookChangeUpdated()); + EventInfoAddressBookChangeRemovedPtr contactsRemoved(new EventInfoAddressBookChangeRemoved()); + + ContactArrayPtr addedContacts(new ContactArray()); + ContactArrayPtr updatedContacts(new ContactArray()); + StringArrayPtr removedContactIds(new StringArray()); + + for(int i = 0; i < addressBookIdCount; i++) + { + int ret = contacts_svc_get_updated_contacts(addressBookIds[i], m_latestVersion, &iter); + if(ret == CTS_SUCCESS) + { + while (contacts_svc_iter_next(iter) == CTS_SUCCESS) + { + CTSstruct *contact= NULL; + CTSvalue *row_info = NULL; + row_info = contacts_svc_iter_get_info(iter); + + changeId = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_ID_INT); + changeType = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_TYPE_INT); + changeVersion = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_VER_INT); + + if(changeType == CTS_OPERATION_INSERTED) + { + contactInserted = true; + contacts_svc_get_contact(changeId, &contact); + + ContactWrapperPtr contactWrapper(new ContactWrapper(m_bookType)); + contactWrapper->setPlatformContact(contact); + ContactPtr absContact = contactWrapper->getAbstractContact(); + if(absContact != NULL) + addedContacts->push_back(absContact); + } + + if(changeType == CTS_OPERATION_UPDATED) + { + contactUpdated = true; + contacts_svc_get_contact(changeId, &contact); + + ContactWrapperPtr contactWrapper(new ContactWrapper(m_bookType)); + contactWrapper->setPlatformContact(contact); + ContactPtr absContact = contactWrapper->getAbstractContact(); + if(absContact != NULL) + updatedContacts->push_back(absContact); + } + + if(changeType == CTS_OPERATION_DELETED) + { + contactDeleted = true; + contacts_svc_get_contact(changeId, &contact); + + ContactWrapperPtr contactWrapper(new ContactWrapper(m_bookType)); + contactWrapper->setPlatformContact(contact); + ContactPtr absContact = contactWrapper->getAbstractContact(); + if(absContact != NULL) + { + if(absContact->getIdIsSet()) + removedContactIds->push_back(absContact->getId()); + } + } + + contacts_svc_value_free(row_info); + } + contacts_svc_iter_remove(iter); + } + } + + m_latestVersion = get_contact_version(); + + if(addressBookIds) + free(addressBookIds); + + if(contactInserted) + { + DPL::Mutex::ScopedLock lock(&m_addressBookEmittersMutex); + contactsAdded->setContacts(addedContacts); + EventInfoAddressBookChangePtr event = DPL::StaticPointerCast(contactsAdded); + EventAddressBookChangeListenerPtr listener(new EventAddressBookChangeListener(event)); + m_addressBookEmitters.emit(listener); + } + + if(contactUpdated) + { + DPL::Mutex::ScopedLock lock(&m_addressBookEmittersMutex); + contactsUpdated->setContacts(updatedContacts); + EventInfoAddressBookChangePtr event = DPL::StaticPointerCast(contactsUpdated); + EventAddressBookChangeListenerPtr listener(new EventAddressBookChangeListener(event)); + m_addressBookEmitters.emit(listener); + } + + if(contactDeleted) + { + DPL::Mutex::ScopedLock lock(&m_addressBookEmittersMutex); + contactsRemoved->setContactIds(removedContactIds); + EventInfoAddressBookChangePtr event = DPL::StaticPointerCast(contactsRemoved); + EventAddressBookChangeListenerPtr listener(new EventAddressBookChangeListener(event)); + m_addressBookEmitters.emit(listener); + } +} + +} // Contact +} // Platform +} // TizenApis diff --git a/src/platform/Tizen/Contact/AddressBook.h b/src/platform/Tizen/Contact/AddressBook.h new file mode 100755 index 0000000..8f7b059 --- /dev/null +++ b/src/platform/Tizen/Contact/AddressBook.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file AddressBook.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _PLATFORM_CONTACT_ADDRESS_BOOK_H_ +#define _PLATFORM_CONTACT_ADDRESS_BOOK_H_ + +#include +#include + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Contact { + +class AddressBook : public TizenApis::Api::Contact::IAddressBook +{ +private: + std::string m_name; + +public: + explicit AddressBook(TizenApis::Api::Contact::IAddressBook::AddressBookType type); + virtual ~AddressBook(); + + virtual std::string getName() const { return m_name; } + virtual void setName(const std::string &value) { m_name = value; }; + + virtual TizenApis::Api::Contact::ContactPropertiesPtr convertFromString(const std::string &vCardStr, + const std::string &format); + virtual std::string convertToString(const TizenApis::Api::Contact::ContactPtr &contact, + const std::string &format); + virtual TizenApis::Api::Contact::ContactPtr add(const TizenApis::Api::Contact::ContactPropertiesPtr &contactProperties); + virtual void update(const TizenApis::Api::Contact::ContactPtr &contact); + virtual void remove(const std::string &id); + + virtual long addChangeListener(const TizenApis::Api::Contact::EventAddressBookChangeListenerEmitterPtr &emitter); + virtual void removeChangeListener(const long watchId); + +protected: + virtual void OnRequestReceived(const TizenApis::Api::Contact::EventAddressBookAddBatchPtr &event); + virtual void OnRequestReceived(const TizenApis::Api::Contact::EventAddressBookUpdateBatchPtr &event); + virtual void OnRequestReceived(const TizenApis::Api::Contact::EventAddressBookRemoveBatchPtr &event); + virtual void OnRequestReceived(const TizenApis::Api::Contact::EventAddressBookFindPtr &event); + +private: + class DownImageInfo + { + private: + DPL::WaitableEvent* m_waitableEvent; + std::string m_downloadedImagePath; + + public: + DownImageInfo() : m_waitableEvent(NULL) + { + } + void setWaitableEvent (DPL::WaitableEvent* waitableEvent) + { + m_waitableEvent = waitableEvent; + } + DPL::WaitableEvent* getWaitableEvent (void) const + { + return m_waitableEvent; + } + void setDownloadedImagePath (const std::string &downloadedImagePath) + { + m_downloadedImagePath = downloadedImagePath; + } + std::string getDownloadedImagePath (void) const + { + return m_downloadedImagePath; + } + }; + static void daNotifyCallback(user_notify_info_t *notify_info, void *user_data); + static void daGetDdInfoCallback(user_dd_info_t *dd_info, void *user_data); + static void daUpdateDownloadInfoCallback(user_download_info_t *download_info, void *user_data); + void setDaClientIdByDaInit(void); + void unsetDaClientIdByDaDeinit(void); + int m_daClientId; + int m_latestVersion; + + std::string downloadImage(const std::string &imgUrl) const; + std::string getRealPath(const std::string &path) const; + + void internalAddContact(const TizenApis::Api::Contact::ContactPtr &newContact); + void internalDeleteContactById(int id); + DPL::Mutex m_contactEditingMutex; + + typedef WrtDeviceApis::Commons::Emitters AddressBookChangedEmitter; + AddressBookChangedEmitter m_addressBookEmitters; + DPL::Mutex m_addressBookEmittersMutex; + +public: + static void contactsSvcContactChangedCallback(void *data); + +private: + void contactsSvcContactChangedCallback(); +}; + +} // Contact +} // Platform +} // TizenApis + +#endif // _PLATFORM_CONTACT_ADDRESS_BOOK_H_ diff --git a/src/platform/Tizen/Contact/ContactFilterValidator.cpp b/src/platform/Tizen/Contact/ContactFilterValidator.cpp new file mode 100755 index 0000000..ac14b7a --- /dev/null +++ b/src/platform/Tizen/Contact/ContactFilterValidator.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactFilterValidator.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "ContactFilterValidator.h" + +namespace TizenApis { +namespace Platform { +namespace Contact { + +using namespace TizenApis::Api::Tizen; + +static PropertyStructArray properties = +{ + {"name.prefix", PrimitiveType_String}, + {"name.firstName", PrimitiveType_String}, + {"name.middleName", PrimitiveType_String}, + {"name.lastName", PrimitiveType_String}, + {"name.nickNames", PrimitiveType_String}, + {"name.phoneticName", PrimitiveType_String}, + {"name.displayName", PrimitiveType_String}, + {"addresses.country", PrimitiveType_String}, + {"addresses.region", PrimitiveType_String}, + {"addresses.city", PrimitiveType_String}, + {"addresses.streetAddress", PrimitiveType_String}, + {"addresses.additionalInformation", PrimitiveType_String}, + {"addresses.postalCode", PrimitiveType_String}, + {"addresses.types", PrimitiveType_String}, + {"photoURI", PrimitiveType_String}, + {"phoneNumbers.number", PrimitiveType_String}, + {"phoneNumbers.types", PrimitiveType_String}, + {"emails.email", PrimitiveType_String}, + {"emails.types", PrimitiveType_String}, + {"birthday", PrimitiveType_Time}, + {"anniversaries.date", PrimitiveType_Time}, + {"organization.name", PrimitiveType_String}, + {"organization.department", PrimitiveType_String}, + {"organization.title", PrimitiveType_String}, + {"organization.role", PrimitiveType_String}, + {"notes", PrimitiveType_String}, + {"urls.url", PrimitiveType_String}, + {"urls.type", PrimitiveType_String}, + {"isFavorite", PrimitiveType_Boolean}, + {"ringtoneURI", PrimitiveType_String}, + {"categories", PrimitiveType_String}, + {0, PrimitiveType_Notype} +}; + +static MatchFlagStrArray matchFlag +{ + "EXACTLY", + "CONTAINS", + "STARTSWITH", + "ENDSWITH", + "EXISTS", + 0 +}; + +FilterValidatorPtr ContactFilterValidatorFactory::getContactFilterValidator() +{ + static FilterValidatorPtr theInstance = + FilterValidatorPtr(new FilterValidator(properties, matchFlag)); + return theInstance; +} + +} // Contact +} // Platform +} // TizenApis diff --git a/src/platform/Tizen/Contact/ContactFilterValidator.h b/src/platform/Tizen/Contact/ContactFilterValidator.h new file mode 100755 index 0000000..a3bf990 --- /dev/null +++ b/src/platform/Tizen/Contact/ContactFilterValidator.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactFilterValidator.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _PLATFORM_CONTACT_CONTACT_FILTER_VALIDATOR_H_ +#define _PLATFORM_CONTACT_CONTACT_FILTER_VALIDATOR_H_ + +#include + +namespace TizenApis { +namespace Platform { +namespace Contact { + +class ContactFilterValidatorFactory : private DPL::Noncopyable +{ +private: + ContactFilterValidatorFactory() + { + } + +public: + static TizenApis::Api::Tizen::FilterValidatorPtr getContactFilterValidator(); +}; + +} // Contact +} // Platform +} // TizenApis + +#endif // _PLATFORM_CONTACT_CONTACT_FILTER_VALIDATOR_H_ diff --git a/src/platform/Tizen/Contact/ContactManager.cpp b/src/platform/Tizen/Contact/ContactManager.cpp new file mode 100755 index 0000000..bf323d0 --- /dev/null +++ b/src/platform/Tizen/Contact/ContactManager.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactManager.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include +#include "ContactManager.h" +#include "AddressBook.h" + +#define DEVICE_ADDRESSBOOK "DEVICE AddressBook" +#define SIM_ADDRESSBOOK "SIM AddressBook" + +namespace TizenApis { +namespace Platform { +namespace Contact { + +using namespace WrtDeviceApis::Commons; +using namespace TizenApis::Api::Contact; +using namespace TizenApis::Api::Tizen; + +//initialize static variables +int ContactManager::m_instanceCount = 0; +bool ContactManager::m_opened = false; + +ContactManager::ContactManager() : + m_deviceBook(new AddressBook(IAddressBook::AddressBookType::PhoneBook)), + m_simBook(new AddressBook(IAddressBook::AddressBookType::SIMBook)) +{ + //set address book names + m_deviceBook->setName(DEVICE_ADDRESSBOOK); + m_simBook->setName(SIM_ADDRESSBOOK); + + //protect for pararel execution + DPL::Mutex::ScopedLock mx(&m_constructorMutex); + if (m_instanceCount == 0) + { + //when it is first instance then open connection to database + if (contacts_svc_connect() == CTS_SUCCESS) + { + //contacts database is opened properly + LogDebug("contacts database is opened properly"); + m_opened = true; + } + else + { + //error during opening contacts database + LogError("error during opening contacts database"); + } + } + + //increase counter of instances + m_instanceCount++; +} + +ContactManager::~ContactManager() +{ +// LogDebug("entered"); + //protect for pararel execution + DPL::Mutex::ScopedLock mx(&m_constructorMutex); + //decrease counter of instances + m_instanceCount--; + if (m_instanceCount == 0) + { + //when it is last instance then clse connection to database + if (contacts_svc_disconnect() != CTS_SUCCESS) + { + //error during closing contacts database + LogError("error during closing contacts database"); + } + m_opened = false; + } +} + +IAddressBookPtr ContactManager::getDefaultAddressBook() +{ + if(!m_opened) + { + //when database is not opened then set result as failed + LogError("Contact DB is not opened."); + ThrowMsg(PlatformException, "Contact DB is not opened."); + } + + return m_deviceBook; +} + +void ContactManager::OnRequestReceived(const EventContactManagerGetAddressBooksPtr &event) +{ + if(!m_opened) + { + //when database is not opened then set result as failed + LogError("Contact DB is not opened."); + event->setResult(false); + event->setExceptionCode(ExceptionCodes::PlatformException); + return; + } + + Try + { + IAddressBookArrayPtr addressBookArray = IAddressBookArrayPtr(new IAddressBookArray()); + + if (m_deviceBook != NULL) + addressBookArray->push_back(m_deviceBook); + if (m_simBook != NULL) + addressBookArray->push_back(m_simBook); + + event->setAddressBooks(addressBookArray); + event->setResult(true); + event->setExceptionCode(ExceptionCodes::None); + } + Catch (UnknownException) + { + LogError("Unknown exception : " << _rethrown_exception.GetMessage()); + event->setResult(false); + event->setExceptionCode(ExceptionCodes::UnknownException); + return; + } +} + +} // Contact +} // Platform +} // TizenApis diff --git a/src/platform/Tizen/Contact/ContactManager.h b/src/platform/Tizen/Contact/ContactManager.h new file mode 100755 index 0000000..f6717b6 --- /dev/null +++ b/src/platform/Tizen/Contact/ContactManager.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactManager.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _PLATFORM_CONTACT_CONTACT_MANAGER_H_ +#define _PLATFORM_CONTACT_CONTACT_MANAGER_H_ + +#include +#include +#include "AddressBook.h" + +namespace TizenApis { +namespace Platform { +namespace Contact { + +class ContactManager: public TizenApis::Api::Contact::IContactManager +{ +public: + ContactManager(); + virtual ~ContactManager(); + + virtual TizenApis::Api::Contact::IAddressBookPtr getDefaultAddressBook(); + +protected: + virtual void OnRequestReceived(const TizenApis::Api::Contact::EventContactManagerGetAddressBooksPtr &event); + +private: + TizenApis::Api::Contact::IAddressBookPtr m_deviceBook; + TizenApis::Api::Contact::IAddressBookPtr m_simBook; + + static int m_instanceCount; + static bool m_opened; + DPL::Mutex m_constructorMutex; +}; + +} // Contact +} // Platform +} // TizenApis + +#endif // _PLATFORM_CONTACT_CONTACT_MANAGER_H_ diff --git a/src/platform/Tizen/Contact/ContactSearchEngine.cpp b/src/platform/Tizen/Contact/ContactSearchEngine.cpp new file mode 100755 index 0000000..e19183c --- /dev/null +++ b/src/platform/Tizen/Contact/ContactSearchEngine.cpp @@ -0,0 +1,870 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactSearchEngine.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "query-svc/query-service.h" +#include "time.h" + +#include +#include +#include "ContactSearchEngine.h" + +namespace TizenApis { +namespace Platform { +namespace Contact { + +using namespace TizenApis::Api::Contact; +using namespace TizenApis::Api::Tizen; +using namespace WrtDeviceApis::Commons; +using namespace std; + +using TizenApis::Api::Contact::Contact; + +map ContactSearchEngine::attrEnumMap = { + {"id", contact_attribute_e::CONTACT_ID}, + {"readOnly", contact_attribute_e::ATTRIBUTE_MAX}, + {"accountId", contact_attribute_e::ATTRIBUTE_MAX}, + {"prefix", contact_attribute_e::NAME_PREFIX}, + {"name.firstName", contact_attribute_e::NAME_FIRST}, + {"name.middleName", contact_attribute_e::NAME_MIDDLE}, + {"name.lastName", contact_attribute_e::NAME_LAST}, + {"name.nicknames", contact_attribute_e::NICKNAME_NAME}, + {"name.phoneticName", contact_attribute_e::NAME_PHONETIC}, + {"name.displayName", contact_attribute_e::NAME_DISPLAY}, + {"addresses.country", contact_attribute_e::ADDRESS_COUNTRY}, + {"addresses.region", contact_attribute_e::ADDRESS_REGION}, + {"addresses.city", contact_attribute_e::ADDRESS_CITY}, + {"addresses.streetAddress", contact_attribute_e::ADDRESS_STREET}, + {"addresses.additionalInformation", contact_attribute_e::ADDRESS_ADDITIONAL}, + {"addresses.postalCode", contact_attribute_e::ADDRESS_POSTAL_CODE}, + {"addresses.types", contact_attribute_e::ATTRIBUTE_MAX}, + {"photoURI", contact_attribute_e::CONTACT_PHOTO_URI}, + {"phoneNumbers.number", contact_attribute_e::NUMBER_ADDRESS}, + {"phoneNumbers.types", contact_attribute_e::NUMBER_TYPES}, + {"emails.email", contact_attribute_e::EMAIL_ADDRESS}, + {"emails.types", contact_attribute_e::EMAIL_TYPE}, + {"birthday", contact_attribute_e::EVENT_DATE}, + {"anniversaries.date", contact_attribute_e::EVENT_DATE}, + {"organizations.name", contact_attribute_e::ORGANIZATION_NAME}, + {"organization.department", contact_attribute_e::ORGANIZATION_DEPARTMENT}, + {"organization.title", contact_attribute_e::ORGANIZATION_TITLE}, + {"organization.role", contact_attribute_e::ORGANIZATION_ROLE}, + {"organization.logoURI", contact_attribute_e::ATTRIBUTE_MAX}, + {"notes", contact_attribute_e::CONTACT_NOTE}, + {"urls.url", contact_attribute_e::URL_ADDRESS}, + {"urls.type", contact_attribute_e::URL_TYPE}, + {"lastUpdated", contact_attribute_e::CONTACT_LAST_UPDATED_TIME_STAMP}, + {"isFavorite", contact_attribute_e::CONTACT_IS_FAVORITE}, + {"ringtoneURI", contact_attribute_e::CONTACT_RINGTONE}, + {"categories", contact_attribute_e::CATEGORY_INFO} +}; + + +ContactSearchEngine::ContactSearchEngine(ContactQueryType type) +{ + query_error error; + query_type_e qtype = query_type_e::QUERY_TO_PERSON; + if (type == CONTACT_QUERY) + qtype = query_type_e::QUERY_TO_CONTACT; + + m_contact_query_service = query_init(&error, qtype); + if (error != QUERY_SUCCESS) + m_contact_query_service = NULL; +} + +ContactSearchEngine::~ContactSearchEngine() +{ + if (m_contact_query_service) + query_finalize(m_contact_query_service); +} + +void ContactSearchEngine::setCondition(FilterPtr filter) +{ + if(!filter) + return; + + IFilterVisitorPtr filterQuery = DPL::StaticPointerCast(SharedFromThis()); + filter->travel(filterQuery); +} + +void ContactSearchEngine::setSortMode(SortModePtr attr) +{ + if(attr) + { + order_e ord; + if (attr->getOrder() == ASCENDING_SORT_ORDER) + ord = ASC; + else + ord = DESC; + + query_set_order_by(m_contact_query_service, getPlatformAttr(attr->getAttributeName()), ord); + } + else + { + query_set_order_by(m_contact_query_service, contact_attribute_e::CONTACT_ID, ASC); + } +} + +void ContactSearchEngine::setAttributeOfInterest(StringArrayPtr attr) +{ + if(attr) + { + m_attributesOfInterest = attr; + for (StringArray::iterator it = attr->begin(); it!=attr->end(); ++it) + { + query_set_attribute(m_contact_query_service, getPlatformAttr(*it)); + } + } + else + { + m_attributesOfInterest = StringArrayPtr(new StringArray()); + for (map::iterator it=attrEnumMap.begin(); it!=attrEnumMap.end(); it++) + { + if(query_set_attribute(m_contact_query_service, static_cast(it->second)) == QUERY_SUCCESS) + m_attributesOfInterest->push_back(it->first); + } + } +} + +ContactArrayPtr ContactSearchEngine::getContactSearchResult() +{ + ContactArrayPtr result = ContactArrayPtr(new ContactArray()); + + query_error err; + + contact_attribute_e pattr; + + bool nameAlreadyChecked = false; + bool numberAlreadyChecked = false; + bool emailAlreadyChecked = false; + bool urlAlreadyChecked = false; + bool addrAlreadyChecked = false; + bool eventAlreadyChecked = false; + bool organizationAlreadyChecked = false; + bool nicknameAlreadyChecked = false; + bool categoryAlreadyChecked = false; + + LogDebug("Start generating result set"); + + while ( query_get_result_contact(m_contact_query_service) == QUERY_SUCCESS ) + { + ContactPtr contact = ContactPtr(new Contact()); + + for (StringArray::iterator it = m_attributesOfInterest->begin(); it != m_attributesOfInterest->end(); it++) + { + pattr = getPlatformAttr(*it); + + err = QUERY_SUCCESS; + + if (!nameAlreadyChecked && + (pattr == CONTACT_ID || pattr == NAME_FIRST || pattr == NAME_LAST || + pattr == NAME_MIDDLE || pattr == NAME_DISPLAY)) + { + char* str; + + str = query_get_attribute(m_contact_query_service, CONTACT_ID, &err); + if( str ) + contact->setId(str); + + str = query_get_attribute(m_contact_query_service, ACCOUNT_ID, &err); + if( str ) + contact->getAccount()->setAccountId(str); + + str = query_get_attribute(m_contact_query_service, CONTACT_IS_FAVORITE, &err); + if( str ) + contact->setIsFavorite(toBool(str)); + + str = query_get_attribute(m_contact_query_service, CONTACT_RINGTONE, &err); + if( str ) + contact->setRingtoneURI(str); + + str = query_get_attribute(m_contact_query_service, CONTACT_NOTE, &err); + if( str ) + { + StringArrayPtr notes(new StringArray()); + notes->push_back(str); + contact->setNotes(notes); + } + + str = query_get_attribute(m_contact_query_service, CONTACT_PHOTO_URI, &err); + if( str ) + contact->setPhotoURI(str); + + str = query_get_attribute(m_contact_query_service, CONTACT_LAST_UPDATED_TIME_STAMP, &err); + if( str ) + { + tm time_stamp; + time_t db_time_stamp = (time_t)atoi(str); + + struct tm* tmp_time = gmtime(&db_time_stamp); + memcpy(&time_stamp, tmp_time, sizeof(tm)); + contact->setLastUpdated(time_stamp); + } + + ContactNamePtr contactName = contact->getName(); + + str = query_get_attribute(m_contact_query_service, NAME_FIRST, &err); + if( str ) + contactName->setFirstName(str); + + str = query_get_attribute(m_contact_query_service, NAME_LAST, &err); + if( str ) + contactName->setLastName(str); + + str = query_get_attribute(m_contact_query_service, NAME_MIDDLE, &err); + if( str ) + contactName->setMiddleName(str); + + str = query_get_attribute(m_contact_query_service, NAME_DISPLAY, &err); + if( str ) + contactName->setDisplayName(str); + + str = query_get_attribute(m_contact_query_service, NAME_PREFIX, &err); + if( str ) + contactName->setPrefix(str); + + str = query_get_attribute(m_contact_query_service, NAME_PHONETIC, &err); + if( str ) + contactName->setPhoneticName(str); + + nameAlreadyChecked = true; + } + else if (!numberAlreadyChecked && (pattr == NUMBER_ADDRESS || pattr == NUMBER_TYPES)) + { + do + { + char *number = query_get_attribute(m_contact_query_service, NUMBER_ADDRESS, &err); + char *numType = query_get_attribute(m_contact_query_service, NUMBER_TYPES, &err); + + setPhoneNumber(contact, number, numType); + + } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS ); + + numberAlreadyChecked = true; + } + else if (!emailAlreadyChecked && (pattr == EMAIL_ADDRESS || pattr == EMAIL_TYPE)) + { + do + { + char *email = query_get_attribute(m_contact_query_service, EMAIL_ADDRESS, &err); + char *emailType = query_get_attribute(m_contact_query_service, EMAIL_TYPE, &err); + + setEmailAddresses(contact, email, emailType); + + } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS ); + + emailAlreadyChecked = true; + } + else if (!urlAlreadyChecked && (pattr == URL_ADDRESS || pattr == URL_TYPE)) + { + do + { + char *url = query_get_attribute(m_contact_query_service, URL_ADDRESS, &err); + char *urlType = query_get_attribute(m_contact_query_service, URL_TYPE, &err); + + setUrlAddresses(contact, url, urlType); + + } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS ); + + urlAlreadyChecked = true; + } + else if (!addrAlreadyChecked && + (pattr == ADDRESS_COUNTRY || pattr == ADDRESS_REGION || + pattr == ADDRESS_CITY || pattr == ADDRESS_STREET || + pattr == ADDRESS_POSTAL_CODE || pattr == ADDRESS_ADDITIONAL) ) + { + do + { + char *country = query_get_attribute(m_contact_query_service, ADDRESS_COUNTRY, &err); + char *region = query_get_attribute(m_contact_query_service, ADDRESS_REGION, &err); + char *city = query_get_attribute(m_contact_query_service, ADDRESS_CITY, &err); + char *street = query_get_attribute(m_contact_query_service, ADDRESS_STREET, &err); + char *postal_code = query_get_attribute(m_contact_query_service, ADDRESS_POSTAL_CODE, &err); + char *additional = query_get_attribute(m_contact_query_service, ADDRESS_ADDITIONAL, &err); + + setAddresses(contact, country, region, city, NULL, street, postal_code, additional); + + } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS ); + + addrAlreadyChecked = true; + } + else if (!eventAlreadyChecked && (pattr == EVENT_DATE || pattr == EVENT_TYPE)) + { + do + { + char *event = query_get_attribute(m_contact_query_service, EVENT_DATE, &err); + char *eventType = query_get_attribute(m_contact_query_service, EVENT_TYPE, &err); + + setEvent(contact, event, eventType); + + } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS ); + + eventAlreadyChecked = true; + } + else if (!organizationAlreadyChecked && + (pattr == ORGANIZATION_NAME || pattr == ORGANIZATION_DEPARTMENT || + pattr == ORGANIZATION_TITLE || pattr == ORGANIZATION_ROLE ) ) + { + do + { + char *orgname = query_get_attribute(m_contact_query_service, ORGANIZATION_NAME, &err); + char *org_dept = query_get_attribute(m_contact_query_service, ORGANIZATION_DEPARTMENT, &err); + char *org_title = query_get_attribute(m_contact_query_service, ORGANIZATION_TITLE, &err); + char *org_role = query_get_attribute(m_contact_query_service, ORGANIZATION_ROLE, &err); + + setOrganization(contact, orgname, org_dept, org_title, org_role); + + } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS ); + + organizationAlreadyChecked = true; + } + else if (!nicknameAlreadyChecked && (pattr == NICKNAME_NAME)) + { + do + { + char *nickname = query_get_attribute(m_contact_query_service, NICKNAME_NAME, &err); + if(nickname) + contact->getName()->addNickname(string(nickname)); + + } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS ); + + nicknameAlreadyChecked = true; + } + else if (!categoryAlreadyChecked && (pattr == CATEGORY_INFO)) + { + do + { + char *category = query_get_attribute(m_contact_query_service, CATEGORY_INFO, &err); + if(category) + contact->addCategory(string(category)); + + } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS ); + + categoryAlreadyChecked = true; + } + + } + nameAlreadyChecked = false; + numberAlreadyChecked = false; + emailAlreadyChecked = false; + urlAlreadyChecked = false; + addrAlreadyChecked = false; + eventAlreadyChecked = false; + organizationAlreadyChecked = false; + nicknameAlreadyChecked = false; + categoryAlreadyChecked = false; + + result->push_back(contact); + } + + LogDebug("entered, end generating result set"); + return result; +} + +void ContactSearchEngine::visitPreComposite(FilterType& type, int depth) +{ + query_set_condition_append(m_contact_query_service, LEFT_BRACKET); +} + +void ContactSearchEngine::visitInComposite(FilterType& type, int depth) +{ + if(type == UNION_FILTER) + query_set_condition_append(m_contact_query_service, OR); + else if(type == INTERSECTION_FILTER) + query_set_condition_append(m_contact_query_service, AND); +} + +void ContactSearchEngine::visitPostComposite(FilterType& type, int depth) +{ + query_set_condition_append(m_contact_query_service, RIGHT_BRACKET); +} + +void ContactSearchEngine::visitAttribute(string& attrName, AnyArrayPtr& matchValues, string& matchFlag, bool caseSensitive, int depth) +{ + contact_attribute_e attr; + attr = getPlatformAttr(attrName); + + string matchValueStr; + + if(matchFlag == "EXISTS") + { + query_set_condition(m_contact_query_service, attr, EXISTS, NULL); + } + else if(attrName == "id" && (matchFlag == "" || matchFlag == "EXACTLY")) + { + visitAttributeID(matchValues); + } + else if(matchValues->size() == 1) + { + condition_e cond; + if(matchFlag == "EXACTLY") + cond = EQUAL; + else if (matchFlag == "STARTSWITH" || matchFlag == "ENDSWITH") + cond = LIKE; + else + cond = EQUAL; + + AnyPtr matchValue = matchValues->at(0); + + visitAttributeEach(attr, matchValue, cond); + } + else if(matchValues->size() > 1) + { + condition_e cond; + if(matchFlag == "EXACTLY") + cond = EQUAL; + else if (matchFlag == "STARTSWITH" || matchFlag == "ENDSWITH") + cond = LIKE; + else + cond = EQUAL; + + query_set_condition_append(m_contact_query_service, LEFT_BRACKET); + + AnyArray::iterator iter; + for(iter = matchValues->begin(); iter != matchValues->end(); iter++) + { + AnyPtr matchValue = *iter; + if(iter != matchValues->begin()) + query_set_condition_append(m_contact_query_service, OR); + + visitAttributeEach(attr, matchValue, cond); + } + + query_set_condition_append(m_contact_query_service, RIGHT_BRACKET); + } +} + +void ContactSearchEngine::visitAttributeRange(string& attrName, AnyPtr& initialValue, AnyPtr& endValue, int depth) +{ + contact_attribute_e attr; + string initialValueStr; + string endValueStr; + + if(initialValue->getType() == PrimitiveType_Time) + { + tm date = DPL::DynamicPointerCast< Any_T >(initialValue)->getValue(); + initialValueStr = toDateDbStr(date); + } + else + { + initialValueStr = initialValue->toString(); + } + + if(endValue->getType() == PrimitiveType_Time) + { + tm date = DPL::DynamicPointerCast< Any_T >(endValue)->getValue(); + endValueStr = toDateDbStr(date); + } + else + { + endValueStr = endValue->toString(); + } + + attr = getPlatformAttr(attrName); + query_set_condition_append(m_contact_query_service, LEFT_BRACKET); + query_set_condition(m_contact_query_service, attr, GREATER_THAN_OR_EQUAL, ("\"" + initialValueStr + "\"").c_str()); + query_set_condition_append(m_contact_query_service, AND); + query_set_condition(m_contact_query_service, attr, LESS_THAN_OR_EQUAL, ("\"" + endValueStr + "\"").c_str()); + query_set_condition_append(m_contact_query_service, RIGHT_BRACKET); +} + +void ContactSearchEngine::visitAttributeEach(contact_attribute_e attr, AnyPtr& matchValue, condition_e flag) +{ + string valueStr; + if(matchValue->getType() == PrimitiveType_Time) + { + tm date = DPL::DynamicPointerCast< Any_T >(matchValue)->getValue(); + valueStr = toDateDbStr(date); + } + else + { + valueStr = matchValue->toString(); + } + + query_set_condition(m_contact_query_service, attr, flag, valueStr.c_str()); +} + +void ContactSearchEngine::visitAttributeID(AnyArrayPtr &ids) +{ + if (ids->size() == 1) + { + query_set_condition(m_contact_query_service, getPlatformAttr("id"), EQUAL, ids->at(0)->toString().c_str()); + } + else if (ids->size() > 1) + { + query_set_condition_with_indices_begin(m_contact_query_service); + + for (AnyArray::iterator iter = ids->begin(); iter != ids->end(); iter++) + query_set_condition_with_indices(m_contact_query_service, (*iter)->toString().c_str()); + + query_set_condition_with_indices_end(m_contact_query_service); + } +} + +contact_attribute_e ContactSearchEngine::getPlatformAttr(string attrName) +{ + contact_attribute_e platformAttr = contact_attribute_e::ATTRIBUTE_MAX; + + platformAttr = (contact_attribute_e) attrEnumMap.find(attrName)->second; + if (platformAttr >= ATTRIBUTE_MAX) + { + ThrowMsg(UnsupportedException, "Attribute(" << attrName << ") is not supported."); + } + + return platformAttr; +} + +#if 0 +void ContactSearchEngine::setPlatformAttrValue(Contact& contact, contact_attribute_e attr, char* val) +{ + if(!val) + return; + + switch (attr) + { + case CONTACT_ID: + contact.setId(string(val)); + break; + case CONTACT_IS_FAVORITE: + contact.setIsFavorite(toBool(val)); + break; + case CONTACT_RINGTONE: + contact.setRingtoneURI(string(val)); + break; + case CONTACT_NOTE: + contact.addNote(string(val)); + break; + case CONTACT_PHOTO_URI: + contact.setPhotoURI(string(val)); + break; +// CONTACT_READ_ONLY, +// CONTACT_SEND_TO_VOICE_MAIL, + case CONTACT_LAST_UPDATED_TIME_STAMP: + contact.setLastUpdated(toDateTm(val)); + break; + +// CONTACT_LATITUDE, +// CONTACT_LONGITUDE, + case NAME_FIRST: + contact.setFirstName(string(val)); + break; + case NAME_MIDDLE: + contact.setMiddleName(string(val)); + break; + case NAME_LAST: + contact.setLastName(string(val)); + break; + case NAME_PREFIX: + contact.setPrefix(string(val)); + break; + case NAME_PHONETIC: + contact.setPhoneticName(string(val)); + break; + case NAME_DISPLAY: + contact.setDisplayName(string(val)); + break; + case NICKNAME_NAME: + contact.addNickname(string(val)); + break; + case NUMBER_ADDRESS: + case NUMBER_TYPES: + break; + case EMAIL_ADDRESS: + case EMAIL_TYPE: + break; + + case URL_ADDRESS: + case URL_TYPE: + break; + + case ADDRESS_COUNTRY: + case ADDRESS_REGION: +// case ADDRESS_COUNTY: + case ADDRESS_CITY: + case ADDRESS_STREET: + case ADDRESS_POSTAL_CODE: + case ADDRESS_ADDITIONAL: + break; + + case CATEGORY_INFO: + contact.addCategory(string(val)); + break; + case EVENT_DATE: + case EVENT_TYPE: + break; + +// ORGANIZATION_NAME = 140, +// ORGANIZATION_DEPARTMENT, +//// ORGANIZATION_OFFICE, +// ORGANIZATION_TITLE, +// ORGANIZATION_ROLE, +//// ORGANIZATION_LOGO_URI, + +// NOT COMPLETE YET +// PRESENCE_STATE = 160, +// PRESENCE_MESSAGE, +// PRESENCE_ICON_URI, +// PRESENCE_CAPABILITY, +// PRESENCE_IM_ADDR, +// +// ATTRIBUTE_MAX = 1000 + default: + break; + } +} +#endif + +void ContactSearchEngine::setPhoneNumber(ContactPtr& contact, char *number, char *type) +{ + if(number == NULL) + return; + + ContactPhoneNumberPtr numberType = ContactPhoneNumberPtr(new ContactPhoneNumber()); + + if(number) + numberType->setNumber(string(number)); + + if(type) + { + vector tokens; + tokenize(type,tokens, ","); + + for (unsigned int i=0; iaddType(tokens[i]); + } + + contact->addPhoneNumber(numberType); +} + +void ContactSearchEngine::setEmailAddresses(ContactPtr& contact, char *email, char *type) +{ + if(email == NULL) + return; + + ContactEmailAddressPtr emailAddr = ContactEmailAddressPtr(new ContactEmailAddress()); + + if(email) + emailAddr->setEmail(string(email)); + + if(type) + { + vector tokens; + tokenize(type,tokens, ","); + for (unsigned int i=0; iaddType(CONTACT_EMAIL_TYPE_WORK); + else if (tokens[i].compare("PREF")) + emailAddr->addType(CONTACT_EMAIL_TYPE_PREF); + else if (tokens[i].compare("HOME")) + emailAddr->addType(CONTACT_EMAIL_TYPE_HOME); + } + } + + contact->addEmail(emailAddr); +} + +void ContactSearchEngine::setUrlAddresses(ContactPtr& contact, char *url, char *type) +{ + if(url == NULL) + return; + + ContactWebSitePtr urlType = ContactWebSitePtr(new ContactWebSite()); + + if(url) + urlType->setUrl(string(url)); + + if(type) + { + vector tokens; + tokenize(type,tokens, ","); + for (unsigned int i=0; isetType(WEBSITE_TYPE_HOMEPAGE); + else if (tokens[i].compare("BLOG") == 0) + urlType->setType(WEBSITE_TYPE_BLOG); + } + } + + contact->addUrl(urlType); +} + +void ContactSearchEngine::setAddresses(ContactPtr& contact, + char *country, char *region, char* city, char *county, char *street, char *postal_code, char *additional) +{ + if(country == NULL && region == NULL && city == NULL && county == NULL && + street == NULL && postal_code == NULL && additional == NULL) + return; + + ContactAddressPtr addr = ContactAddressPtr(new ContactAddress()); + + if(country) + addr->setCountry(string(country)); + + if(region) + addr->setRegion(string(region)); + + if(city) + addr->setCity(string(city)); + + if(street) + addr->setStreetAddress(string(street)); + + if(postal_code) + addr->setPostalCode(string(postal_code)); + + if(additional) + addr->setAdditionalInformation(string(additional)); + + contact->addAddress(addr); +} + +void ContactSearchEngine::setEvent(ContactPtr& contact, char *date, char *type) +{ + if(date == NULL) + return; + + tm tm_date = toDateTmFromDateDbStr(date); + + if(type != NULL) + { + if(strcmp(type, "BIRTHDAY") == 0) + { + contact->setBirthday(tm_date); + } + else if(strcmp(type, "ANNIVERSARY") == 0) + { + ContactAnniversaryPtr anniv = ContactAnniversaryPtr(new ContactAnniversary()); + + anniv->setDate(tm_date); + //if(type) + // anniv->setLabel(string(type)); + + contact->addAnniversary(anniv); + } + } + else + LogDebug("type is null"); +} + +void ContactSearchEngine::setOrganization(ContactPtr& contact, + char* org_name, char* org_dept, char* org_title, char* org_role) +{ + ContactOrganizationPtr org = ContactOrganizationPtr(new ContactOrganization()); + + if(org_name) + org->setName(string(org_name)); + + if(org_dept) + org->setDepartment(string(org_dept)); + + if(org_title) + org->setTitle(string(org_title)); + + if(org_role) + org->setRole(string(org_role)); + + contact->setOrganization(org); +} + +void ContactSearchEngine::tokenize(const string& str, vector& tokens, const string& delimiters) +{ + // Skip delimiters at beginning. + string::size_type lastPos = str.find_first_not_of(delimiters, 0); + // Find first "non-delimiter". + string::size_type pos = str.find_first_of(delimiters, lastPos); + + while (string::npos != pos || string::npos != lastPos) + { + // Found a token, add it to the vector. + tokens.push_back(str.substr(lastPos, pos - lastPos)); + // Skip delimiters. Note the "not_of" + lastPos = str.find_first_not_of(delimiters, pos); + // Find next "non-delimiter" + pos = str.find_first_of(delimiters, lastPos); + } +} + +bool ContactSearchEngine::toBool(char* val) +{ + string boolStr(val); + + if (boolStr == "true" || boolStr == "TRUE") + return true; + + return false; +} + +tm ContactSearchEngine::toDateTm(char* arg) +{ + // this code originated from Converter + struct tm result; + char* currentLocale = setlocale(LC_TIME, NULL); + if (currentLocale == NULL) { + ThrowMsg(ConversionException, "Couldn't get current locale."); + } + DPL::ScopedFree currentLocaleCopy(strdup(currentLocale)); + if (setlocale(LC_TIME, "C") == NULL) { + ThrowMsg(ConversionException, "Couldn't set POSIX locale."); + } + if (strptime(arg, "%a %b %d %Y %T", &result) == NULL) { + ThrowMsg(ConversionException, "Couldn't convert supplied date."); + } + if (setlocale(LC_TIME, currentLocaleCopy.Get()) == NULL) { + ThrowMsg(ConversionException, "Couldn't set previous locale back."); + } + return result; +} + +string ContactSearchEngine::toDateDbStr(const tm &date) const +{ + stringstream ss; + ss << setfill('0') << setiosflags(ios::right) << setw(4) << (date.tm_year + 1900); + ss << setfill('0') << setiosflags(ios::right) << setw(2) << (date.tm_mon + 1); + ss << setfill('0') << setiosflags(ios::right) << setw(2) << date.tm_mday; + + return ss.str(); +} + +tm ContactSearchEngine::toDateTmFromDateDbStr(const char* arg) const +{ + tm date; + + if(arg == NULL) { + ThrowMsg(InvalidArgumentException, "Invalid Date type"); + } + + int dateDb; + stringstream ss(arg); + ss >> dateDb; + + date.tm_year = (dateDb / 10000) - 1900; + date.tm_mon = ((dateDb - ((date.tm_year + 1900) * 10000)) / 100) - 1; + date.tm_mday = (dateDb - ((date.tm_year + 1900) * 10000) - date.tm_mon * 100); + + return date; +} + +} // Contact +} // Platform +} // TizenApis diff --git a/src/platform/Tizen/Contact/ContactSearchEngine.h b/src/platform/Tizen/Contact/ContactSearchEngine.h new file mode 100755 index 0000000..825e649 --- /dev/null +++ b/src/platform/Tizen/Contact/ContactSearchEngine.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactSearchEngine.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _PLATFORM_CONTACT_CONTACT_SEARCH_ENGINE_H_ +#define _PLATFORM_CONTACT_CONTACT_SEARCH_ENGINE_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "query-svc/query-service.h" + +namespace TizenApis { +namespace Platform { +namespace Contact { + +class ContactSearchEngine : + public TizenApis::Api::Tizen::IFilterVisitor, + public DPL::EnableSharedFromThis +{ +public: + enum ContactQueryType + { + PERSON_QUERY, + CONTACT_QUERY, + }; + + ContactSearchEngine(ContactQueryType); + virtual ~ContactSearchEngine(); + + // setting search options. + void setCondition(TizenApis::Api::Tizen::FilterPtr filter); + void setAttributeOfInterest(TizenApis::Api::Contact::StringArrayPtr attr = TizenApis::Api::Contact::StringArrayPtr(NULL)); + void setSortMode(TizenApis::Api::Tizen::SortModePtr attr = TizenApis::Api::Tizen::SortModePtr(NULL)); + + // getting results + TizenApis::Api::Contact::ContactArrayPtr getContactSearchResult(); + + // inherited from IFilterVisitor + virtual void visitPreComposite(TizenApis::Api::Tizen::FilterType& type, int depth); + virtual void visitInComposite(TizenApis::Api::Tizen::FilterType& type, int depth); + virtual void visitPostComposite(TizenApis::Api::Tizen::FilterType& type, int depth); + virtual void visitAttribute(std::string& attrName, + TizenApis::Api::Tizen::AnyArrayPtr& matchValues, + std::string& matchFlag, + bool caseSensitive, + int depth); + virtual void visitAttributeRange(std::string& attrName, + TizenApis::Api::Tizen::AnyPtr& initialValue, + TizenApis::Api::Tizen::AnyPtr& endValue, + int depth); + +private: + static std::map attrEnumMap; + + ADVANCED_HANDLE m_contact_query_service; + TizenApis::Api::Contact::StringArrayPtr m_attributesOfInterest; + + void visitAttributeEach(contact_attribute_e attr, TizenApis::Api::Tizen::AnyPtr& value, condition_e flag); + void visitAttributeID(TizenApis::Api::Tizen::AnyArrayPtr &ids); + + contact_attribute_e getPlatformAttr(std::string attrName); +#if 0 + void setPlatformAttrValue(TizenApis::Api::Contact::Contact& contact, contact_attribute_e attr, char* val); +#endif + + void setPhoneNumber(TizenApis::Api::Contact::ContactPtr& contact, char *number, char *type); + void setEmailAddresses(TizenApis::Api::Contact::ContactPtr& contact, char *email, char *type); + void setUrlAddresses(TizenApis::Api::Contact::ContactPtr& contact, char *url, char *type); + void setAddresses(TizenApis::Api::Contact::ContactPtr& contact, char *country, char *region, char* city, char *county, char *street, char *postal_code, char *additional); + void setEvent(TizenApis::Api::Contact::ContactPtr& contact, char *date, char *type); + void setOrganization(TizenApis::Api::Contact::ContactPtr& contact, char* org_name, char* org_dept, char* org_title, char* org_role); + + // utility functions + void tokenize(const std::string& str, std::vector& tokens, const std::string& delimiters = " "); + bool toBool(char* val); + std::tm toDateTm(char* arg); + std::string toDateDbStr(const std::tm &date) const; + std::tm toDateTmFromDateDbStr(const char* arg) const; +}; + +typedef DPL::SharedPtr ContactSearchEnginePtr; + +} // Contact +} // Platform +} // TizenApis + +#endif // _PLATFORM_CONTACT_CONTACT_SEARCH_ENGINE_H_ diff --git a/src/platform/Tizen/Contact/ContactWrapper.cpp b/src/platform/Tizen/Contact/ContactWrapper.cpp new file mode 100755 index 0000000..7ed4fce --- /dev/null +++ b/src/platform/Tizen/Contact/ContactWrapper.cpp @@ -0,0 +1,2047 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactWrapper.cpp + * @author Lukasz Marek(l.marek@samsung.com) + * @author Yujie Zeng(yj.zengk@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include "ContactWrapper.h" +#include "AddressBook.h" +#include "query-svc/query-service.h" + +#define CONTACT_ATTRIBUTE_PHONETIC_NAME "phoneticName" + +namespace TizenApis +{ +namespace Platform +{ +namespace Contact +{ + +using namespace TizenApis::Api::Contact; +using namespace WrtDeviceApis::Commons; +using namespace std; + +using TizenApis::Api::Contact::Contact; + +ContactWrapper::ContactWrapper(IAddressBook::AddressBookType type) : + m_abstractContact(NULL), + m_platformContact(NULL) +{ + //platform layer seems to not support different storage types yet + /* + if ( type == IAddressBook::PhoneBook ) + { + } + else if ( type == IAddressBook::SIMBook ) + { + } + else + { + LogError("invalid storage type"); + } + */ +} + +ContactWrapper::~ContactWrapper() +{ + freePlatformObject(); +} + +void ContactWrapper::freePlatformObject() +{ + if (m_platformContact) + { + contacts_svc_struct_free(m_platformContact); + m_platformContact = NULL; + } +} + +void ContactWrapper::freeAbstractObject() +{ + m_abstractContact = ContactPtr(NULL); +} + +ContactPtr ContactWrapper::getAbstractContact() const +{ + return m_abstractContact; +} + +void ContactWrapper::setAbstractContact(const ContactPtr &contact, bool isConvertingVCard) +{ + m_abstractContact = contact; + convertToPlatformObject(isConvertingVCard); +} + +CTSstruct* ContactWrapper::getPlatformContact() const +{ + return m_platformContact; +} + +void ContactWrapper::setPlatformContact(CTSstruct* contact) +{ + freePlatformObject(); + m_platformContact = contact; + convertToAbstractObject(); +} + +bool ContactWrapper::convertToPlatformObject(bool isConvertingVCard) +{ + LogDebug("entered"); + + freePlatformObject(); + + if (!m_abstractContact) + { + LogError("abstract object is not set"); + return false; + } + + //if abstrat object has id set then we have to read existing object and update it + if (m_abstractContact->getIdIsSet() && (isConvertingVCard == false)) + { + LogDebug("reading existing contact"); + contacts_svc_get_contact(atoi(m_abstractContact->getId().c_str()), &m_platformContact); + } + else // if no id is set then create new platform object + { + LogDebug("creating new contact"); + m_platformContact = contacts_svc_struct_new(CTS_STRUCT_CONTACT); + } + + if (!m_platformContact) + { + LogError("contact structure not created properly"); + return false; + } + + Try + { + if (!convertToPlatformBaseData()) + ThrowMsg(UnknownException, "error during converting base data"); + + if (!convertToPlatformAddressObject()) + ThrowMsg(UnknownException, "error during converting address object"); + + if (!convertToPlatformEmailObject()) + ThrowMsg(UnknownException, "error during converting email object"); + + if (!convertToPlatformPhoneObject()) + ThrowMsg(UnknownException, "error during converting phone object"); + + if (!convertToPlatformNicknameObject()) + ThrowMsg(UnknownException, "error during converting nickname object"); + + if (!convertToPlatformPhoneticnameObject()) + ThrowMsg(UnknownException, "error during converting Phoneticname object"); + + if (!convertToPlatformGroupObject()) + ThrowMsg(UnknownException, "error during converting group object"); + + if (!convertToPlatformUrlObject()) + ThrowMsg(UnknownException, "error during converting url object"); + + if (!convertToPlatformOrganizationObject()) + ThrowMsg(UnknownException, "error during converting organization object"); + + if (!convertToPlatformAnniversaryObject()) + ThrowMsg(UnknownException, "error during converting anniversary object"); + + if (!convertToPlatformbirthdayObject()) + ThrowMsg(UnknownException, "error during converting birthday object"); + } + Catch (Exception) + { + LogError("Error converting to platform object : " << _rethrown_exception.GetMessage()); + + freePlatformObject(); + + return false; + } + + return true; +} + +bool ContactWrapper::convertToAbstractObject() +{ + LogDebug("entered"); + + freeAbstractObject(); + + if (!m_platformContact) + return false; + + CTSvalue *value = NULL; + //store id + if (CTS_SUCCESS != contacts_svc_struct_get_value(m_platformContact, CTS_CF_BASE_INFO_VALUE, &value)) + return false; + + m_abstractContact = ContactPtr(new Contact()); + m_abstractContact->setId(contacts_svc_value_get_int(value, CTS_BASE_VAL_ID_INT)); + + const char *charValue; + + charValue = contacts_svc_value_get_str(value, CTS_BASE_VAL_IMG_PATH_STR); + if (charValue) + m_abstractContact->setPhotoURI(charValue); + + charValue = contacts_svc_value_get_str(value, CTS_BASE_VAL_RINGTONE_PATH_STR); + if (charValue) + m_abstractContact->setRingtoneURI(charValue); + + charValue = contacts_svc_value_get_str(value, CTS_BASE_VAL_NOTE_STR); + if (charValue) + { + StringArrayPtr notes(new StringArray()); + notes->push_back(charValue); + m_abstractContact->setNotes(notes); + } + + Try + { + if (!convertToAbstractBaseData()) + ThrowMsg(UnknownException, "error during converting base data"); + + if (!convertToAbstractAddressObject()) + ThrowMsg(UnknownException, "error during converting address object"); + + if (!convertToAbstractEmailObject()) + ThrowMsg(UnknownException, "error during converting email object"); + + if (!convertToAbstractPhoneObject()) + ThrowMsg(UnknownException, "error during converting phone object"); + + if (!convertToAbstractNicknameObject()) + ThrowMsg(UnknownException, "error during converting nickname object"); + + if (!convertToAbstractPhoneticnameObject()) + ThrowMsg(UnknownException, "error during converting phoneticName object"); + + if (!convertToAbstractGroupObject()) + ThrowMsg(UnknownException, "error during converting group object"); + + if (!convertToAbstractUrlObject()) + ThrowMsg(UnknownException, "error during converting url object"); + + if (!convertToAbstractOrganizationObject()) + ThrowMsg(UnknownException, "error during converting organization object"); + + if (!convertToAbstractAnniversaryObject()) + ThrowMsg(UnknownException, "error during converting anniversary object"); + + if (!convertToAbstractBirthdayObject()) + ThrowMsg(UnknownException, "error during converting birthday object"); + } + Catch (Exception) + { + LogError("Error converting to abstract object : " << _rethrown_exception.GetMessage()); + freeAbstractObject(); + + return false; + } + + return true; +} + +bool ContactWrapper::convertToAbstractBaseData() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + CTSvalue *value = NULL; + + int errorCode; + errorCode = contacts_svc_struct_get_value(m_platformContact, CTS_CF_NAME_VALUE, &value); + if (CTS_SUCCESS == errorCode && value != NULL) + { + const char *charValue = NULL; + ContactNamePtr contactName = m_abstractContact->getName(); + + charValue = contacts_svc_value_get_str(value, CTS_NAME_VAL_FIRST_STR); + if (charValue) + contactName->setFirstName(charValue); + + charValue = contacts_svc_value_get_str(value, CTS_NAME_VAL_ADDITION_STR); + if (charValue) + contactName->setMiddleName(charValue); + + charValue = contacts_svc_value_get_str(value, CTS_NAME_VAL_LAST_STR); + if (charValue) + contactName->setLastName(charValue); + + charValue = contacts_svc_value_get_str(value, CTS_NAME_VAL_DISPLAY_STR); + if (charValue) + contactName->setDisplayName(charValue); + + charValue = contacts_svc_value_get_str(value, CTS_NAME_VAL_PREFIX_STR); + if (charValue) + contactName->setPrefix(charValue); + + charValue = contacts_svc_value_get_str(value, CTS_NAME_VAL_SUFFIX_STR); + if (charValue) + contactName->setPhoneticName(charValue); + + } + else if (errorCode != CTS_ERR_NO_DATA || value == NULL) + { + return false; + } + + return true; +} + +bool ContactWrapper::convertToAbstractAddressObject() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + ContactAddressArrayPtr addresses = ContactAddressArrayPtr(new ContactAddressArray()); + + GSList *addressList = NULL; + int errorCode = contacts_svc_struct_get_list(m_platformContact, CTS_CF_POSTAL_ADDR_LIST, &addressList); + if (CTS_SUCCESS == errorCode) + { + for (; addressList; addressList = g_slist_next(addressList)) + { + ContactAddressPtr address(new ContactAddress()); + addresses->push_back(address); + + int type = contacts_svc_value_get_int(static_cast(addressList->data), CTS_POSTAL_VAL_TYPE_INT); + switch (type) + { + case CTS_ADDR_TYPE_NONE: + address->addType(CONTACT_ADDRESS_TYPE_PREF); + break; + case CTS_ADDR_TYPE_HOME: + address->addType(CONTACT_ADDRESS_TYPE_HOME); + break; + case CTS_ADDR_TYPE_WORK: + address->addType(CONTACT_ADDRESS_TYPE_WORK); + break; + default: + LogError("invalid address type"); + address->addType(CONTACT_ADDRESS_TYPE_PREF); + break; + } + + const char *charValue = NULL; + + charValue = contacts_svc_value_get_str(static_cast(addressList->data), CTS_POSTAL_VAL_COUNTRY_STR); + if (charValue) + address->setCountry(charValue); + + charValue = contacts_svc_value_get_str(static_cast(addressList->data), CTS_POSTAL_VAL_REGION_STR); + if (charValue) + address->setRegion(charValue); + + charValue = contacts_svc_value_get_str(static_cast(addressList->data), CTS_POSTAL_VAL_LOCALITY_STR); + if (charValue) + address->setCity(charValue); + + charValue = contacts_svc_value_get_str(static_cast(addressList->data), CTS_POSTAL_VAL_STREET_STR); + if (charValue) + address->setStreetAddress(charValue); + + charValue = contacts_svc_value_get_str(static_cast(addressList->data), CTS_POSTAL_VAL_POSTALCODE_STR); + if (charValue) + address->setPostalCode(charValue); + + charValue = contacts_svc_value_get_str(static_cast(addressList->data), CTS_POSTAL_VAL_EXTENDED_STR); + if (charValue) + address->setAdditionalInformation(charValue); + + } + } + else if (errorCode != CTS_ERR_NO_DATA) + { + return false; + } + + m_abstractContact->setAddresses(addresses); + + return true; +} + +bool ContactWrapper::convertToAbstractUrlObject() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + ContactWebSiteArrayPtr urls = ContactWebSiteArrayPtr(new ContactWebSiteArray()); + + GSList *urlList = NULL; + int errorCode = contacts_svc_struct_get_list(m_platformContact, CTS_CF_WEB_ADDR_LIST, &urlList); + if (CTS_SUCCESS == errorCode) + { + for (; urlList; urlList = g_slist_next(urlList)) + { + ContactWebSitePtr url(new ContactWebSite()); + urls->push_back(url); + + int type = contacts_svc_value_get_int(static_cast(urlList->data), CTS_WEB_VAL_TYPE_INT); + switch (type) + { + case CTS_WEB_TYPE_NONE: + url->setType(WEBSITE_TYPE_HOMEPAGE); + break; + case CTS_WEB_TYPE_HOME: + url->setType(WEBSITE_TYPE_HOMEPAGE); + break; + case CTS_WEB_TYPE_WORK: + url->setType(WEBSITE_TYPE_BLOG); + break; + default: + LogError("invalid url type"); + url->setType(WEBSITE_TYPE_HOMEPAGE); + break; + } + + const char *charValue = NULL; + + charValue = contacts_svc_value_get_str(static_cast(urlList->data), CTS_WEB_VAL_ADDR_STR); + if (charValue) + url->setUrl(charValue); + + } + } + else if (errorCode != CTS_ERR_NO_DATA) + { + return false; + } + + m_abstractContact->setUrls(urls); + + return true; +} + +bool ContactWrapper::convertToAbstractOrganizationObject() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + CTSvalue *value = NULL; + int errorCode; + + ContactOrganizationPtr organization(new ContactOrganization()); + + errorCode = contacts_svc_struct_get_value(m_platformContact, CTS_CF_COMPANY_VALUE, &value); + if (CTS_SUCCESS == errorCode) + { + const char *charValue = NULL; + + charValue = contacts_svc_value_get_str(value, CTS_COMPANY_VAL_NAME_STR); + if (charValue) + organization->setName(charValue); + + charValue = contacts_svc_value_get_str(value, CTS_COMPANY_VAL_DEPARTMENT_STR); + if (charValue) + organization->setDepartment(charValue); + + charValue = contacts_svc_value_get_str(value, CTS_COMPANY_VAL_JOB_TITLE_STR); + if (charValue) + organization->setTitle(charValue); + + charValue = contacts_svc_value_get_str(value, CTS_COMPANY_VAL_ROLE_STR); + if (charValue) + organization->setRole(charValue); + + } + else if (errorCode != CTS_ERR_NO_DATA) + { + return false; + } + + m_abstractContact->setOrganization(organization); + + return true; +} + +bool ContactWrapper::convertToAbstractAnniversaryObject() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + ContactAnniversaryArrayPtr anniversaries(new ContactAnniversaryArray()); + + GSList *eventList = NULL; + int errorCode = contacts_svc_struct_get_list(m_platformContact, CTS_CF_EVENT_LIST, &eventList); + if (CTS_SUCCESS == errorCode) + { + for (; eventList; eventList = g_slist_next(eventList)) + { + int type = contacts_svc_value_get_int(static_cast(eventList->data), CTS_EVENT_VAL_TYPE_INT); + int db_date = contacts_svc_value_get_int(static_cast(eventList->data), CTS_EVENT_VAL_DATE_INT); + + if (type == CTS_EVENT_TYPE_ANNIVERSARY) + { + ContactAnniversaryPtr anniversary = ContactAnniversaryPtr(new ContactAnniversary()); + + tm tm_date; + + tm_date.tm_year = (db_date / 10000) - 1900; + tm_date.tm_mon = ((db_date - ((tm_date.tm_year + 1900) * 10000)) / 100) - 1; + tm_date.tm_mday = (db_date - ((tm_date.tm_year + 1900) * 10000) - tm_date.tm_mon * 100); + + anniversary->setDate(tm_date); + + //if (type) + // anniv->setLabel(string("ANNIVERSARY")); + + anniversaries->push_back(anniversary); + } + } + } + else if (errorCode != CTS_ERR_NO_DATA) + { + return false; + } + + m_abstractContact->setAnniversaries(anniversaries); + + return true; +} + +bool ContactWrapper::convertToAbstractBirthdayObject() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + GSList *eventList = NULL; + int errorCode = contacts_svc_struct_get_list(m_platformContact, CTS_CF_EVENT_LIST, &eventList); + if (CTS_SUCCESS == errorCode) + { + for (; eventList; eventList = g_slist_next(eventList)) + { + int type = contacts_svc_value_get_int(static_cast(eventList->data), CTS_EVENT_VAL_TYPE_INT); + int db_date = contacts_svc_value_get_int(static_cast(eventList->data), CTS_EVENT_VAL_DATE_INT); + + if (type == CTS_EVENT_TYPE_BIRTH) + { + tm tm_date; + + tm_date.tm_year = (db_date / 10000) - 1900; + tm_date.tm_mon = ((db_date - ((tm_date.tm_year + 1900) * 10000)) / 100) - 1; + tm_date.tm_mday = (db_date - ((tm_date.tm_year + 1900) * 10000) - tm_date.tm_mon * 100); + + m_abstractContact->setBirthday(tm_date); + break; + } + } + } + else if (errorCode != CTS_ERR_NO_DATA) + { + return false; + } + + return true; +} + +bool ContactWrapper::convertToAbstractEmailObject() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + ContactEmailAddressArrayPtr emailAddresses(new ContactEmailAddressArray()); + + GSList *emailList = NULL; + int errorCode = contacts_svc_struct_get_list(m_platformContact, CTS_CF_EMAIL_LIST, &emailList); + if (CTS_SUCCESS == errorCode) + { + for (; emailList; emailList = g_slist_next(emailList)) + { + ContactEmailAddressPtr email(new ContactEmailAddress()); + + emailAddresses->push_back(email); + + int type = contacts_svc_value_get_int(static_cast(emailList->data), CTS_EMAIL_VAL_TYPE_INT); + switch (type) + { + case CTS_EMAIL_TYPE_NONE: + email->addType(CONTACT_EMAIL_TYPE_PREF); + break; + case CTS_EMAIL_TYPE_HOME: + email->addType(CONTACT_EMAIL_TYPE_HOME); + break; + case CTS_EMAIL_TYPE_WORK: + email->addType(CONTACT_EMAIL_TYPE_WORK); + break; + default: + LogError("invalid phone type"); + email->addType(CONTACT_EMAIL_TYPE_PREF); + break; + } + + const char *charValue = NULL; + + charValue = contacts_svc_value_get_str(static_cast(emailList->data), CTS_EMAIL_VAL_ADDR_STR); + if (charValue) + email->setEmail(charValue); + } + } + else if (errorCode != CTS_ERR_NO_DATA) + { + return false; + } + + m_abstractContact->setEmails(emailAddresses); + + return true; +} + +bool ContactWrapper::convertToAbstractPhoneObject() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + ContactPhoneNumberArrayPtr phoneNumbers(new ContactPhoneNumberArray()); + + GSList *phoneList = NULL; + int errorCode = contacts_svc_struct_get_list(m_platformContact, CTS_CF_NUMBER_LIST, &phoneList); + if (CTS_SUCCESS == errorCode) + { + for (; phoneList; phoneList = g_slist_next(phoneList)) + { + ContactPhoneNumberPtr phoneNumber(new ContactPhoneNumber()); + phoneNumbers->push_back(phoneNumber); + + int type = contacts_svc_value_get_int(static_cast(phoneList->data), CTS_NUM_VAL_TYPE_INT); + switch (type) + { + case CTS_NUM_TYPE_WORK: + phoneNumber->addType("WORK"); + break; + case CTS_NUM_TYPE_NONE: + phoneNumber->addType("PREF"); + break; + case CTS_NUM_TYPE_HOME: + phoneNumber->addType("HOME"); + break; + case CTS_NUM_TYPE_FAX: + phoneNumber->addType("FAX"); + break; + case CTS_NUM_TYPE_CELL: + phoneNumber->addType("CELL"); + break; + case CTS_NUM_TYPE_PAGER: + phoneNumber->addType("PAGER"); + break; + case CTS_NUM_TYPE_CAR: + phoneNumber->addType("CAR"); + break; + case CTS_NUM_TYPE_VOICE: + phoneNumber->addType("VOICE"); + break; + case CTS_NUM_TYPE_MSG: + phoneNumber->addType("MSG"); + break; + case CTS_NUM_TYPE_BBS: + phoneNumber->addType("BBS"); + break; + case CTS_NUM_TYPE_MODEM: + phoneNumber->addType("MODEM"); + break; + case CTS_NUM_TYPE_ISDN: + phoneNumber->addType("ISDN"); + break; + case CTS_NUM_TYPE_VIDEO: + phoneNumber->addType("VIDEO"); + break; + case CTS_NUM_TYPE_PCS: + phoneNumber->addType("PCS"); + break; + default: + LogError("invalid phone type"); + phoneNumber->addType("PREF"); + break; + } + + const char *charValue = NULL; + + charValue = contacts_svc_value_get_str(static_cast(phoneList->data), CTS_NUM_VAL_NUMBER_STR); + if (charValue) + phoneNumber->setNumber(charValue); + } + } + else if (errorCode != CTS_ERR_NO_DATA) + { + return false; + } + + m_abstractContact->setPhoneNumbers(phoneNumbers); + + return true; +} + +bool ContactWrapper::convertToAbstractNicknameObject() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + StringArrayPtr nickNames(new StringArray()); + + GSList *nicknNameList = NULL; + int errorCode = contacts_svc_struct_get_list(m_platformContact, CTS_CF_NICKNAME_LIST, &nicknNameList); + if (CTS_SUCCESS == errorCode) + { + for (; nicknNameList; nicknNameList = g_slist_next(nicknNameList)) + { + const char *charValue = NULL; + charValue = contacts_svc_value_get_str(static_cast(nicknNameList->data), CTS_NICKNAME_VAL_NAME_STR); + if (charValue) + nickNames->push_back(charValue); + } + } + else if (errorCode != CTS_ERR_NO_DATA) + { + return false; + } + + m_abstractContact->getName()->setNicknames(nickNames); + + return true; +} + +bool ContactWrapper::convertToAbstractPhoneticnameObject() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + int structFieldType = 0; + structFieldType = getCustomTypeInContactsSvc(CONTACT_ATTRIBUTE_PHONETIC_NAME); + if (structFieldType < CTS_SUCCESS) + { + LogError("Phonetic name struct type is not found!!"); + return false; + } + + CTSvalue *value = NULL; + int errorCode; + errorCode = contacts_svc_struct_get_value(m_platformContact, static_cast(structFieldType), &value); + if (CTS_SUCCESS == errorCode) + { + if (value) + { + const char *charValue = NULL; + charValue = contacts_svc_value_get_str(value, CTS_EXTEND_VAL_DATA2_STR); + if (charValue) + m_abstractContact->getName()->setPhoneticName(charValue); + } + else + { + return false; + } + } + else if (errorCode != CTS_ERR_NO_DATA) + { + return false; + } + + return true; +} + +bool ContactWrapper::convertToAbstractGroupObject() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + StringArrayPtr categories(new StringArray()); + + GSList *groupList = NULL; + int errorCode = contacts_svc_struct_get_list(m_platformContact, CTS_CF_GROUPREL_LIST, &groupList); + if (CTS_SUCCESS == errorCode) + { + for (; groupList; groupList = g_slist_next(groupList)) + { + const char *charValue = NULL; + charValue = contacts_svc_value_get_str(static_cast(groupList->data), CTS_GROUPREL_VAL_NAME_STR); + if (charValue) + categories->push_back(charValue); + } + } + else if (errorCode != CTS_ERR_NO_DATA) + { + return false; + } + + m_abstractContact->setCategories(categories); + + return true; +} + +bool ContactWrapper::convertToPlatformNicknameObject() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + StringArrayPtr nicknames = m_abstractContact->getName()->getNicknames(); + + bool properlyCreated = true; + + GSList *nicknameList = NULL; + if (CTS_SUCCESS == contacts_svc_struct_get_list(m_platformContact, CTS_CF_NICKNAME_LIST, &nicknameList)) + { + GSList *nicknameListSave = nicknameList; + for (; nicknameList; nicknameList = g_slist_next(nicknameList)) + { + CTSvalue* nickname = static_cast(nicknameList->data); + contacts_svc_value_set_bool(nickname, CTS_NICKNAME_VAL_DELETE_BOOL, true); + } + nicknameList = nicknameListSave; + } + + if (nicknames->size() == 0 && nicknameList == NULL) + return true; + + //add new items + for (size_t i = 0; i < nicknames->size(); ++i) + { + CTSvalue *nickname = NULL; + nickname = contacts_svc_value_new(CTS_VALUE_NICKNAME); + if (nickname) + { + if (CTS_SUCCESS == contacts_svc_value_set_str(nickname, CTS_NICKNAME_VAL_NAME_STR, nicknames->at(i).c_str())) + { + nicknameList = g_slist_append(nicknameList, nickname); + } + else + { + contacts_svc_value_free(nickname); + properlyCreated = false; + break; + } + } + else + { + properlyCreated = false; + break; + } + } + + if (properlyCreated) + { + if (CTS_SUCCESS != contacts_svc_struct_store_list(m_platformContact, CTS_CF_NICKNAME_LIST, nicknameList)) + { + properlyCreated = false; + } + } + + return properlyCreated; +} + +bool ContactWrapper::convertToPlatformPhoneticnameObject() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + int structFieldType = 0; + structFieldType = getCustomTypeInContactsSvc(CONTACT_ATTRIBUTE_PHONETIC_NAME); + if (structFieldType < CTS_SUCCESS) + { + LogError("Phonetic name struct type is not found!!"); + return false; + } + + /** + *If phonetic name information is not existed, add phonetic name information + *If phonetic name information is existed,update phonetic name information + */ + CTSvalue *value = NULL; + if (CTS_SUCCESS != contacts_svc_struct_get_value(m_platformContact, static_cast(structFieldType), &value)) + { + value = contacts_svc_value_new(CTS_VALUE_EXTEND); + if (!value) + return false; + + } + + if (CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_EXTEND_VAL_DATA2_STR, m_abstractContact->getName()->getPhoneticName().c_str()) + || CTS_SUCCESS != contacts_svc_struct_store_value(m_platformContact, static_cast(structFieldType), value)) + { + contacts_svc_value_free(value); + return false; + } + + contacts_svc_value_free(value); + +// LogDebug("RETURN TRUE!!!"); + return true; +} + +bool ContactWrapper::convertToPlatformGroupObject() +{ +// LogDebug("entered"); + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + StringArrayPtr groups = m_abstractContact->getCategories(); + CTSvalue *group = NULL; + bool properlyCreated = true; + GSList *groupList = NULL; + //mark existing items to delete them. + if (CTS_SUCCESS == contacts_svc_struct_get_list(m_platformContact, CTS_CF_GROUPREL_LIST, &groupList)) + { + GSList *groupListSave = groupList; + for (; groupList; groupList = g_slist_next(groupList)) + { +// LogDebug("clearing group list"); + CTSvalue* delgroup = static_cast(groupList->data); + contacts_svc_value_set_bool(delgroup, CTS_GROUPREL_VAL_DELETE_BOOL, true); + } + groupList = groupListSave; + } + if (groups->size() == 0 && groupList == NULL + ) + return true; + + //add new items + query_error error_code = QUERY_SUCCESS; + GSList *groups_list = NULL; + int accountId; + + try { + string accountIdStr = m_abstractContact->getAccount()->getAccountId(); + stringstream ss(accountIdStr); + ss >> accountId; + } catch (...) { + LogError("Wrong account id"); + return false; + } + + int addressBookId = find_addressbook_id(accountId, &error_code); + if (error_code != QUERY_SUCCESS) + addressBookId = 0; + + CTSiter* group_iter; + bool is_new_group = true; + + for (size_t i = 0; i < groups->size(); ++i) + { + if (CTS_SUCCESS == contacts_svc_get_list(CTS_LIST_ALL_GROUP, &group_iter)) + { + while (CTS_SUCCESS == contacts_svc_iter_next(group_iter)) + { + CTSvalue *findgroup = contacts_svc_iter_get_info(group_iter); + if (findgroup) + { + group_info_t* group_info = g_new0(group_info_t, 1); + + group_info->group_name = g_strdup(contacts_svc_value_get_str(findgroup, CTS_LIST_GROUP_NAME_STR)); + group_info->addressbook_id = contacts_svc_value_get_int(findgroup, CTS_GROUP_VAL_ADDRESSBOOK_ID_INT); + group_info->group_id = contacts_svc_value_get_int(findgroup, CTS_GROUP_VAL_ID_INT); + groups_list = g_slist_append(groups_list, group_info); + } + } + } + + group = contacts_svc_value_new(CTS_VALUE_GROUP_RELATION); + if (group) + { + int groupId = -1; + //groupId = AddressBook::getGroupId(groups[i]); + + is_new_group = true; + GSList* tmp_list = groups_list; + while (tmp_list) + { + group_info_t* info = (group_info_t*) tmp_list->data; + + if ((info->group_name != NULL) && (groups->at(i).compare(info->group_name) == 0) + && (info->addressbook_id == addressBookId)) + { + is_new_group = false; + groupId = info->group_id; + } + if (info->group_name) + free(info->group_name); + free(info); + tmp_list = g_slist_next(tmp_list); + } + g_slist_free(groups_list); + groups_list = NULL; + + if (is_new_group) + { + CTSvalue *new_group; + new_group = contacts_svc_value_new(CTS_VALUE_GROUP); + + contacts_svc_value_set_str(new_group, CTS_GROUP_VAL_NAME_STR, (const char*) (groups->at(i).c_str())); + contacts_svc_value_set_int(new_group, CTS_GROUP_VAL_ADDRESSBOOK_ID_INT, addressBookId); + groupId = contacts_svc_insert_group(addressBookId, new_group); + if (groupId < 0) + return false; + contacts_svc_value_free(new_group); + } +// LogDebug("group id " << groupId); + if (groupId != -1) + { + if (CTS_SUCCESS == contacts_svc_value_set_int(group, CTS_GROUPREL_VAL_ID_INT, groupId)) + { + groupList = g_slist_append(groupList, group); + } + else + { + contacts_svc_value_free(group); + properlyCreated = false; + break; + } + } + else + { + contacts_svc_value_free(group); + properlyCreated = false; + break; + } + } + else + { + properlyCreated = false; + break; + } + } + if (properlyCreated) + { +// LogDebug("storing group list"); + if (CTS_SUCCESS != contacts_svc_struct_store_list(m_platformContact, CTS_CF_GROUPREL_LIST, groupList)) + { + properlyCreated = false; + } + } + for (; groupList; groupList = g_slist_next(groupList)) + { + contacts_svc_value_free(static_cast(groupList->data)); + } + g_slist_free(groupList); + return properlyCreated; +} + +bool ContactWrapper::convertToPlatformUrlObject() +{ +// LogDebug("entered"); + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + int type = 0; + ContactWebSiteArrayPtr urls = m_abstractContact->getUrls(); + CTSvalue *url = NULL; + bool properlyCreated = true; + GSList *urlList = NULL; + //mark existing items to delete them. + if (CTS_SUCCESS == contacts_svc_struct_get_list(m_platformContact, CTS_CF_WEB_ADDR_LIST, &urlList)) + { + GSList *urlListSave = urlList; + for (; urlList; urlList = g_slist_next(urlList)) + { +// LogDebug("clearing url list"); + CTSvalue* tmp_email = static_cast(urlList->data); + contacts_svc_value_set_bool(tmp_email, CTS_WEB_VAL_DELETE_BOOL, true); + } + urlList = urlListSave; + } + if (urls->size() == 0 && urlList == NULL + ) + return true; + + //add new items + for (size_t i = 0; i < urls->size(); ++i) + { + ContactWebSiteType types = urls->at(i)->getType(); + url = contacts_svc_value_new(CTS_VALUE_WEB); + if (url) + { + switch (types) + { + case WEBSITE_TYPE_HOMEPAGE: + type = CTS_WEB_TYPE_HOME; + break; + case WEBSITE_TYPE_BLOG: + type = CTS_WEB_TYPE_WORK; + break; + default: + LogError("invalid phone type"); + type = CTS_WEB_TYPE_NONE; + break; + } + if (CTS_SUCCESS == contacts_svc_value_set_int(url, CTS_WEB_VAL_TYPE_INT, type) + && CTS_SUCCESS == contacts_svc_value_set_str(url, CTS_WEB_VAL_ADDR_STR, urls->at(i)->getUrl().c_str())) + { + urlList = g_slist_append(urlList, url); + } + else + { + contacts_svc_value_free(url); + properlyCreated = false; + break; + } + } + else + { + properlyCreated = false; + break; + } + + if (!properlyCreated) + { + break; + } + } + + if (properlyCreated) + { + if (CTS_SUCCESS != contacts_svc_struct_store_list(m_platformContact, CTS_CF_WEB_ADDR_LIST, urlList)) + { + properlyCreated = false; + } + } + for (; urlList; urlList = g_slist_next(urlList)) + { + contacts_svc_value_free(static_cast(urlList->data)); + } + g_slist_free(urlList); + return properlyCreated; +} + +bool ContactWrapper::convertToPlatformOrganizationObject() +{ +// LogDebug("entered"); + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + ContactOrganizationPtr org = m_abstractContact->getOrganization(); + CTSvalue *organization = NULL; + + //mark existing items to delete them. + if (CTS_SUCCESS != contacts_svc_struct_get_value(m_platformContact, CTS_CF_COMPANY_VALUE, &organization)) + { + CTSvalue *value = contacts_svc_value_new(CTS_VALUE_COMPANY); + if (value) + { + if (CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_COMPANY_VAL_NAME_STR, org->getName().c_str()) + || CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_COMPANY_VAL_DEPARTMENT_STR, org->getDepartment().c_str()) + || CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_COMPANY_VAL_JOB_TITLE_STR, org->getTitle().c_str()) + || CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_COMPANY_VAL_ROLE_STR, org->getRole().c_str()) + || CTS_SUCCESS != contacts_svc_struct_store_value(m_platformContact, CTS_CF_COMPANY_VALUE, value)) + { + contacts_svc_value_free(value); + return false; + } + contacts_svc_value_free(value); + } + else + { + return false; + } + } + else + { + contacts_svc_value_set_str(organization, CTS_COMPANY_VAL_NAME_STR, org->getName().c_str()); + contacts_svc_value_set_str(organization, CTS_COMPANY_VAL_DEPARTMENT_STR, org->getDepartment().c_str()); + contacts_svc_value_set_str(organization, CTS_COMPANY_VAL_JOB_TITLE_STR, org->getTitle().c_str()); + contacts_svc_value_set_str(organization, CTS_COMPANY_VAL_ROLE_STR, org->getRole().c_str()); + contacts_svc_struct_store_value(m_platformContact, CTS_CF_COMPANY_VALUE, organization); + contacts_svc_value_free(organization); + } + + return true; +} + +bool ContactWrapper::convertToPlatformAnniversaryObject() +{ +// LogDebug("entered"); + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + ContactAnniversaryArrayPtr anniversaries = m_abstractContact->getAnniversaries(); + CTSvalue *anniversary = NULL; + bool properlyCreated = true; + GSList *anniversaryList = NULL; + + //mark existing items to delete them. + if (CTS_SUCCESS == contacts_svc_struct_get_list(m_platformContact, CTS_CF_EVENT_LIST, &anniversaryList)) + { + GSList *anniversaryListSave = anniversaryList; + for (; anniversaryList; anniversaryList = g_slist_next(anniversaryList)) + { +// LogDebug("clearing anniversary list"); + CTSvalue* tmp_anniversary = static_cast(anniversaryList->data); + contacts_svc_value_set_bool(tmp_anniversary, CTS_EVENT_VAL_DELETE_BOOL, true); + } + anniversaryList = anniversaryListSave; + } + if (anniversaries->size() == 0 && anniversaryList == NULL + ) + return true; + + //add new items + int date = 0; + for (size_t i = 0; i < anniversaries->size(); ++i) + { + date = 0; + std::tm abstract_date = anniversaries->at(i)->getDate(); + + date = (abstract_date.tm_year + 1900) * 10000 + (abstract_date.tm_mon+1) * 100 + abstract_date.tm_mday; + anniversary = contacts_svc_value_new(CTS_VALUE_EVENT); + if (anniversary) + { + if (CTS_SUCCESS == contacts_svc_value_set_int(anniversary, CTS_EVENT_VAL_TYPE_INT, CTS_EVENT_TYPE_ANNIVERSARY) + && CTS_SUCCESS == contacts_svc_value_set_int(anniversary, CTS_EVENT_VAL_DATE_INT, date)) + { + anniversaryList = g_slist_append(anniversaryList, anniversary); + } + else + { + contacts_svc_value_free(anniversary); + properlyCreated = false; + break; + } + } + else + { + properlyCreated = false; + break; + } + + if (!properlyCreated) + { + break; + } + } + + if (properlyCreated) + { + if (CTS_SUCCESS != contacts_svc_struct_store_list(m_platformContact, CTS_CF_EVENT_LIST, anniversaryList)) + { + properlyCreated = false; + } + } + for (; anniversaryList; anniversaryList = g_slist_next(anniversaryList)) + { + contacts_svc_value_free(static_cast(anniversaryList->data)); + } + g_slist_free(anniversaryList); + return properlyCreated; +} + +bool ContactWrapper::convertToPlatformbirthdayObject() +{ +// LogDebug("entered"); + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + tm birth_date = m_abstractContact->getBirthday(); + + CTSvalue *birthday = NULL; + bool properlyCreated = true; + GSList *anniversaryList = NULL; + + //mark existing items to delete them. + if (CTS_SUCCESS == contacts_svc_struct_get_list(m_platformContact, CTS_CF_EVENT_LIST, &anniversaryList)) + { + GSList *anniversaryListSave = anniversaryList; + for (; anniversaryList; anniversaryList = g_slist_next(anniversaryList)) + { +// LogDebug("clearing anniversary list"); + CTSvalue* tmp_anniversary = static_cast(anniversaryList->data); + int type = contacts_svc_value_get_int(tmp_anniversary, CTS_EVENT_VAL_TYPE_INT); + if (type == CTS_EVENT_TYPE_BIRTH) + contacts_svc_value_set_bool(tmp_anniversary, CTS_EVENT_VAL_DELETE_BOOL, true); + } + anniversaryList = anniversaryListSave; + } + if (birth_date.tm_year == 0 && birth_date.tm_mon == 0 && birth_date.tm_mday == 0 && anniversaryList == NULL + ) + return true; + + //add new items + int date = 0; + date = (birth_date.tm_year + 1900) * 10000 + (birth_date.tm_mon+1) * 100 + birth_date.tm_mday; +// for (size_t i = 0; i < anniversaries->size(); ++i) { + birthday = contacts_svc_value_new(CTS_VALUE_EVENT); + if (birthday) + { + + if (CTS_SUCCESS == contacts_svc_value_set_int(birthday, CTS_EVENT_VAL_TYPE_INT, CTS_EVENT_TYPE_BIRTH) + && CTS_SUCCESS == contacts_svc_value_set_int(birthday, CTS_EVENT_VAL_DATE_INT, date)) + { + anniversaryList = g_slist_append(anniversaryList, birthday); + } + else + { + contacts_svc_value_free(birthday); + properlyCreated = false; +// break; + } + } + else + { + properlyCreated = false; +// break; + } + +// if (!properlyCreated) { +// break; +// } +// } + + if (properlyCreated) + { + if (CTS_SUCCESS != contacts_svc_struct_store_list(m_platformContact, CTS_CF_EVENT_LIST, anniversaryList)) + { + properlyCreated = false; + } + } + for (; anniversaryList; anniversaryList = g_slist_next(anniversaryList)) + { + contacts_svc_value_free(static_cast(anniversaryList->data)); + } + g_slist_free(anniversaryList); + return properlyCreated; +} + +bool ContactWrapper::convertToPlatformPhoneObject() +{ +// LogDebug("entered"); + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + int type = 0; + ContactPhoneNumberArrayPtr phoneNumbers = m_abstractContact->getPhoneNumbers(); + bool properlyCreated = true; + CTSvalue *number = NULL; + GSList *numberList = NULL; + //mark existing items to delete them. + if (CTS_SUCCESS == contacts_svc_struct_get_list(m_platformContact, CTS_CF_NUMBER_LIST, &numberList)) + { + GSList *numberListSave = numberList; + for (; numberList; numberList = g_slist_next(numberList)) + { +// LogDebug("clearing phone list"); + CTSvalue* number = static_cast(numberList->data); + contacts_svc_value_set_bool(number, CTS_NUM_VAL_DELETE_BOOL, true); + } + numberList = numberListSave; + } + if (phoneNumbers->size() == 0 && numberList == NULL ) + return true; + + //add new items + for (size_t i = 0; i < phoneNumbers->size(); ++i) + { + StringArrayPtr types = phoneNumbers->at(i)->getTypes(); + number = contacts_svc_value_new(CTS_VALUE_NUMBER); + type = 0; + if (number) + { + for (size_t j = 0; j < types->size(); ++j) + { + if (types->at(j) == "WORK") + { + type = type | CTS_NUM_TYPE_WORK; + } + else if (types->at(j) == "PREF") + { + type = type | CTS_NUM_TYPE_NONE; + } + else if (types->at(j) == "HOME") + { + type = type | CTS_NUM_TYPE_HOME; + } + else if (types->at(j) == "FAX") + { + type = type | CTS_NUM_TYPE_FAX; + } + else if (types->at(j) == "CELL") + { + type = type | CTS_NUM_TYPE_CELL; + } + else if (types->at(j) == "PAGER") + { + type = type | CTS_NUM_TYPE_PAGER; + } + else if (types->at(j) == "CAR") + { + type = type | CTS_NUM_TYPE_CAR; + } + else if (types->at(j) == "BBS") + { + type = type | CTS_NUM_TYPE_BBS; + } + else if (types->at(j) == "MODEM") + { + type = type | CTS_NUM_TYPE_MODEM; + } + else if (types->at(j) == "ISDN") + { + type = type | CTS_NUM_TYPE_ISDN; + } + else if (types->at(j) == "VIDEO") + { + type = type | CTS_NUM_TYPE_VIDEO; + } + else if (types->at(j) == "VOICE") + { + type = type | CTS_NUM_TYPE_VOICE; + } + else if (types->at(j) == "MSG") + { + type = type | CTS_NUM_TYPE_MSG; + } + else + { + LogError("invalid phone type"); + type = CTS_NUM_TYPE_NONE; + } + } + if (CTS_SUCCESS == contacts_svc_value_set_str(number, CTS_NUM_VAL_NUMBER_STR, phoneNumbers->at(i)->getNumber().c_str()) + && CTS_SUCCESS == contacts_svc_value_set_bool(number, CTS_NUM_VAL_DEFAULT_BOOL, type == CTS_NUM_TYPE_NONE) + && CTS_SUCCESS == contacts_svc_value_set_int(number, CTS_NUM_VAL_TYPE_INT, type)) + { + numberList = g_slist_append(numberList, number); + } + else + { + contacts_svc_value_free(number); + properlyCreated = false; + break; + } + } + else + { + properlyCreated = false; + break; + } + if (!properlyCreated) + { + break; + } + } + if (properlyCreated) + { + if (CTS_SUCCESS != contacts_svc_struct_store_list(m_platformContact, CTS_CF_NUMBER_LIST, numberList)) + { + properlyCreated = false; + } + } + for (; numberList; numberList = g_slist_next(numberList)) + { + contacts_svc_value_free(static_cast(numberList->data)); + } + g_slist_free(numberList); + return properlyCreated; +} + +bool ContactWrapper::convertToPlatformEmailObject() +{ +// LogDebug("entered"); + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + int type = 0; + ContactEmailAddressArrayPtr emails = m_abstractContact->getEmails(); + CTSvalue *email = NULL; + bool properlyCreated = true; + GSList *emailList = NULL; + //mark existing items to delete them. + if (CTS_SUCCESS == contacts_svc_struct_get_list(m_platformContact, CTS_CF_EMAIL_LIST, &emailList)) + { + GSList *emailListSave = emailList; + for (; emailList; emailList = g_slist_next(emailList)) + { +// LogDebug("clearing email list"); + CTSvalue* email = static_cast(emailList->data); + contacts_svc_value_set_bool(email, CTS_EMAIL_VAL_DELETE_BOOL, true); + } + emailList = emailListSave; + } + if (emails->size() == 0 && emailList == NULL) + return true; + + //add new items + for (size_t i = 0; i < emails->size(); ++i) + { + ContactEmailAddressTypeArrayPtr types = emails->at(i)->getTypes(); + email = contacts_svc_value_new(CTS_VALUE_EMAIL); + type = 0; + if (email) + { + for (size_t j = 0; j < types->size(); ++j) + { + switch (types->at(j)) + { + case CONTACT_EMAIL_TYPE_HOME: + type = type | CTS_EMAIL_TYPE_HOME; + break; + case CONTACT_EMAIL_TYPE_WORK: + type = type | CTS_EMAIL_TYPE_WORK; + break; + case CONTACT_EMAIL_TYPE_PREF: + type = type | CTS_EMAIL_TYPE_NONE; + break; + default: + LogError("invalid phone type"); + type = CTS_EMAIL_TYPE_NONE; + break; + } + } + if (CTS_SUCCESS == contacts_svc_value_set_int(email, CTS_EMAIL_VAL_TYPE_INT, type) + && CTS_SUCCESS == contacts_svc_value_set_str(email, CTS_EMAIL_VAL_ADDR_STR, emails->at(i)->getEmail().c_str())) + { + emailList = g_slist_append(emailList, email); + } + else + { + contacts_svc_value_free(email); + properlyCreated = false; + break; + } + } + else + { + properlyCreated = false; + break; + } + + if (!properlyCreated) + { + break; + } + } + if (properlyCreated) + { + if (CTS_SUCCESS != contacts_svc_struct_store_list(m_platformContact, CTS_CF_EMAIL_LIST, emailList)) + { + properlyCreated = false; + } + } + for (; emailList; emailList = g_slist_next(emailList)) + { + contacts_svc_value_free(static_cast(emailList->data)); + } + g_slist_free(emailList); + return properlyCreated; +} + +bool ContactWrapper::convertToPlatformAddressObject() +{ +// LogDebug("entered"); + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + int type = 0; + ContactAddressArrayPtr addresses = m_abstractContact->getAddresses(); + bool properlyCreated = true; + + GSList *addressList = NULL; + if (CTS_SUCCESS == contacts_svc_struct_get_list(m_platformContact, CTS_CF_POSTAL_ADDR_LIST, &addressList)) + { + GSList *addressListSave = addressList; + for (; addressList; addressList = g_slist_next(addressList)) + { +// LogDebug("clearing address list"); + CTSvalue* address = static_cast(addressList->data); + contacts_svc_value_set_bool(address, CTS_POSTAL_VAL_DELETE_BOOL, true); + } + addressList = addressListSave; + } + if (addresses->size() == 0 && addressList == NULL) + return true; + + //add new items + for (size_t i = 0; i < addresses->size(); ++i) + { + ContactAddressTypeArrayPtr types = addresses->at(i)->getTypes(); + + CTSvalue *address = NULL; + address = contacts_svc_value_new(CTS_VALUE_POSTAL); + if (address) + { + type = 0; + for (size_t j = 0; j < types->size(); ++j) + { + switch (types->at(j)) + { + case CONTACT_ADDRESS_TYPE_PREF: + type = CTS_ADDR_TYPE_NONE; + break; + case CONTACT_ADDRESS_TYPE_WORK: + type = CTS_ADDR_TYPE_WORK; + break; + case CONTACT_ADDRESS_TYPE_HOME: + type = CTS_ADDR_TYPE_HOME; + break; + default: + LogError("invalid address type"); + type = CTS_EMAIL_TYPE_NONE; + break; + } + } + if (CTS_SUCCESS == contacts_svc_value_set_int(address, CTS_POSTAL_VAL_TYPE_INT, type) + && CTS_SUCCESS == contacts_svc_value_set_str(address, CTS_POSTAL_VAL_COUNTRY_STR, addresses->at(i)->getCountry().c_str()) + && CTS_SUCCESS == contacts_svc_value_set_str(address, CTS_POSTAL_VAL_REGION_STR, addresses->at(i)->getRegion().c_str()) + && CTS_SUCCESS == contacts_svc_value_set_str(address, CTS_POSTAL_VAL_LOCALITY_STR, addresses->at(i)->getCity().c_str()) + && CTS_SUCCESS == contacts_svc_value_set_str(address, CTS_POSTAL_VAL_STREET_STR, addresses->at(i)->getStreetAddress().c_str()) + && CTS_SUCCESS == contacts_svc_value_set_str(address, CTS_POSTAL_VAL_POBOX_STR, addresses->at(i)->getAdditionalInformation().c_str()) + && CTS_SUCCESS == contacts_svc_value_set_str(address, CTS_POSTAL_VAL_POSTALCODE_STR, addresses->at(i)->getPostalCode().c_str()) + && CTS_SUCCESS == contacts_svc_value_set_str(address, CTS_POSTAL_VAL_EXTENDED_STR, addresses->at(i)->getAdditionalInformation().c_str())) + { + addressList = g_slist_append(addressList, address); + } + else + { + contacts_svc_value_free(address); + properlyCreated = false; + break; + } + } + else + { + properlyCreated = false; + break; + } + + if (!properlyCreated) + { + break; + } + } + + if (properlyCreated) + { + if (CTS_SUCCESS != contacts_svc_struct_store_list(m_platformContact, CTS_CF_POSTAL_ADDR_LIST, addressList)) + { + properlyCreated = false; + } + } + for (; addressList; addressList = g_slist_next(addressList)) + { + contacts_svc_value_free(static_cast(addressList->data)); + } + + g_slist_free(addressList); + + return properlyCreated; +} + +bool ContactWrapper::convertToPlatformBaseData() +{ + if (NULL == m_abstractContact) + { + LogError("you should create empty abstract contact object first"); + return false; + } + + if (NULL == m_platformContact) + { + LogError("you should provide platform contact object first"); + return false; + } + + /** + *If name information is not existed, add name information + * If name information is existed,update name information + */ + CTSvalue *value = NULL; + + if (CTS_SUCCESS != contacts_svc_struct_get_value(m_platformContact, CTS_CF_NAME_VALUE, &value)) + { + CTSvalue *value = contacts_svc_value_new(CTS_VALUE_NAME); + if (value) + { + ContactNamePtr contactName = m_abstractContact->getName(); + if (CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_NAME_VAL_FIRST_STR, contactName->getFirstName().c_str()) + || CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_NAME_VAL_LAST_STR, contactName->getLastName().c_str()) + || CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_NAME_VAL_ADDITION_STR, contactName->getMiddleName().c_str()) + || CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_NAME_VAL_DISPLAY_STR, contactName->getDisplayName().c_str()) + || CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_NAME_VAL_PREFIX_STR, contactName->getPrefix().c_str()) + || CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_NAME_VAL_SUFFIX_STR, contactName->getPhoneticName().c_str()) + || CTS_SUCCESS != contacts_svc_struct_store_value(m_platformContact, CTS_CF_NAME_VALUE, value)) + { + contacts_svc_value_free(value); + return false; + } + contacts_svc_value_free(value); + } + else + { + return false; + } + } + else + { + ContactNamePtr contactName = m_abstractContact->getName(); + if (CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_NAME_VAL_FIRST_STR, contactName->getFirstName().c_str()) + || CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_NAME_VAL_LAST_STR, contactName->getLastName().c_str()) + || CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_NAME_VAL_ADDITION_STR, contactName->getMiddleName().c_str()) + || CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_NAME_VAL_DISPLAY_STR, contactName->getDisplayName().c_str()) + || CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_NAME_VAL_SUFFIX_STR, contactName->getPhoneticName().c_str()) + || CTS_SUCCESS != contacts_svc_value_set_str(value, CTS_NAME_VAL_PREFIX_STR, contactName->getPrefix().c_str())) + { + contacts_svc_value_free(value); + return false; + } + contacts_svc_value_free(value); + } + + /** + *If photo and ringtone uri information is not existed, add the information + * If photo and ringtone uri is existed,update the information + */ + CTSvalue *baseinfo = NULL; + if (CTS_SUCCESS != contacts_svc_struct_get_value(m_platformContact, CTS_CF_BASE_INFO_VALUE, &baseinfo)) + { + + baseinfo = contacts_svc_value_new(CTS_VALUE_CONTACT_BASE_INFO); + if (baseinfo) + { + if (m_abstractContact->getPhotoURIIsSet()) + { + if (CTS_SUCCESS != contacts_svc_value_set_str(baseinfo, CTS_BASE_VAL_IMG_PATH_STR, m_abstractContact->getPhotoURI().c_str())) + { + contacts_svc_value_free(baseinfo); + return false; + } + } + + if (CTS_SUCCESS != contacts_svc_value_set_str(baseinfo, CTS_BASE_VAL_RINGTONE_PATH_STR, m_abstractContact->getRingtoneURI().c_str())) + { + contacts_svc_value_free(baseinfo); + return false; + } + + if (CTS_SUCCESS != contacts_svc_value_set_bool(baseinfo, CTS_BASE_VAL_FAVORITE_BOOL, m_abstractContact->getIsFavorite())) + { + contacts_svc_value_free(baseinfo); + return false; + } + + if(m_abstractContact->getNotesNum() > 0) + { + if (CTS_SUCCESS != contacts_svc_value_set_str(baseinfo, CTS_BASE_VAL_NOTE_STR, m_abstractContact->getNotes()->at(0).c_str())) + { + contacts_svc_value_free(baseinfo); + return false; + } + } + + contacts_svc_struct_store_value(m_platformContact, CTS_CF_BASE_INFO_VALUE, baseinfo); + contacts_svc_value_free(baseinfo); + } + else + { + return false; + } + } + else + { + const char * oldimgpath = NULL; + oldimgpath = contacts_svc_value_get_str(baseinfo, CTS_BASE_VAL_IMG_PATH_STR); + + string strOldImagePath = ""; + if (NULL != oldimgpath) + { + strOldImagePath = static_cast(oldimgpath); + } + + string strNewImagePath = m_abstractContact->getPhotoURI(); + if (strOldImagePath != strNewImagePath) + { + if (CTS_SUCCESS != contacts_svc_value_set_str(baseinfo, CTS_BASE_VAL_IMG_PATH_STR, strNewImagePath.c_str())) + { + contacts_svc_value_free(value); + return false; + } + } + + if (CTS_SUCCESS != contacts_svc_value_set_str(baseinfo, CTS_BASE_VAL_RINGTONE_PATH_STR, m_abstractContact->getRingtoneURI().c_str())) + { + return false; + } + + if(m_abstractContact->getNotesNum() > 0) + { + if (CTS_SUCCESS != contacts_svc_value_set_str(baseinfo, CTS_BASE_VAL_NOTE_STR, m_abstractContact->getNotes()->at(0).c_str())) + { + contacts_svc_value_free(baseinfo); + return false; + } + } + else + { + if (CTS_SUCCESS != contacts_svc_value_set_str(baseinfo, CTS_BASE_VAL_NOTE_STR, "")) + { + contacts_svc_value_free(baseinfo); + return false; + } + } + + contacts_svc_struct_store_value(m_platformContact, CTS_CF_BASE_INFO_VALUE, baseinfo); + contacts_svc_value_free(value); + } + /* + //save company information + CTSvalue *company = NULL; + company = contacts_svc_value_new(CTS_VALUE_COMPANY); + if (company) { + if (m_abstractContact->getOrganizations()->size() > 0) { + if (CTS_SUCCESS != + contacts_svc_value_set_str(company, CTS_COMPANY_VAL_NAME_STR, + m_abstractContact->getOrganizations()->at(0)->getName().c_str()) + || + CTS_SUCCESS != + contacts_svc_struct_store_value(m_platformContact, + CTS_CF_COMPANY_VALUE, company)) + { + contacts_svc_value_free(company); + return false; + } + } + contacts_svc_value_free(value); + } else { + return false; + } + */ + return true; +} + +int ContactWrapper::getCustomTypeInContactsSvc(const string &typeName) const +{ + int structFieldType = -1; + structFieldType = contacts_svc_find_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, const_cast(typeName.c_str())); + if ( CTS_ERR_DB_RECORD_NOT_FOUND == structFieldType) + { + LogDebug("CTS_ERR_DB_RECORD_NOT_FOUND!!"); + + structFieldType = contacts_svc_insert_custom_type( CTS_TYPE_CLASS_EXTEND_DATA, const_cast(typeName.c_str())); + if (CTS_SUCCESS > structFieldType) + { + LogDebug("Create fail"); + } + } + else if (CTS_SUCCESS > structFieldType) + { + LogDebug("contacts_svc_find_custom_type is fail"); + } + + return structFieldType; +} + +void ContactWrapper::printPlatformObject() +{ +} + +void ContactWrapper::printAbstractObject() +{ +} + +} // Contact +} // Platform +} // TizenApis diff --git a/src/platform/Tizen/Contact/ContactWrapper.h b/src/platform/Tizen/Contact/ContactWrapper.h new file mode 100755 index 0000000..b12caad --- /dev/null +++ b/src/platform/Tizen/Contact/ContactWrapper.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactManager.h + * @author + * @version 0.1 + * @brief + */ + +#ifndef _PLATFORM_CONTACT_CONTACT_WRAPPER_H_ +#define _PLATFORM_CONTACT_CONTACT_WRAPPER_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Contact { + +class ContactWrapper +{ +public: + explicit ContactWrapper(TizenApis::Api::Contact::IAddressBook::AddressBookType type); + virtual ~ContactWrapper(); + + TizenApis::Api::Contact::ContactPtr getAbstractContact() const; + void setAbstractContact(const TizenApis::Api::Contact::ContactPtr &contact, bool is_convert_vCard); + + CTSstruct* getPlatformContact() const; + //WARNING: calling this function will cause to store pointer inside private field + //Structure will be freed by this class when is not needed anymore. + //User should not modify nor free passed pointer. + void setPlatformContact(CTSstruct* contact); + +protected: + bool convertToPlatformObject(bool is_convert_vCard); + bool convertToAbstractObject(); + + TizenApis::Api::Contact::ContactPtr m_abstractContact; + CTSstruct* m_platformContact; + +private: + void freePlatformObject(); + void freeAbstractObject(); + + bool convertToPlatformBaseData(); + bool convertToPlatformAddressObject(); + bool convertToPlatformEmailObject(); + bool convertToPlatformPhoneObject(); + bool convertToPlatformNicknameObject(); + bool convertToPlatformPhoneticnameObject(); + bool convertToPlatformGroupObject(); + bool convertToPlatformUrlObject(); + bool convertToPlatformOrganizationObject(); + bool convertToPlatformAnniversaryObject(); + bool convertToPlatformbirthdayObject(); + + bool convertToAbstractBaseData(); + bool convertToAbstractAddressObject(); + bool convertToAbstractEmailObject(); + bool convertToAbstractPhoneObject(); + bool convertToAbstractNicknameObject(); + bool convertToAbstractPhoneticnameObject(); + bool convertToAbstractGroupObject(); + bool convertToAbstractUrlObject(); + bool convertToAbstractOrganizationObject(); + bool convertToAbstractAnniversaryObject(); + bool convertToAbstractBirthdayObject(); + + int getCustomTypeInContactsSvc(const std::string &typeName) const; + //for debug purpose only + void printPlatformObject(); + //for debug purpose only + void printAbstractObject(); +}; + +typedef DPL::SharedPtr ContactWrapperPtr; + +} // Contact +} // Platform +} // TizenApis + +#endif // _PLATFORM_CONTACT_CONTACT_WRAPPER_H_ diff --git a/src/platform/Tizen/Contact/config.cmake b/src/platform/Tizen/Contact/config.cmake new file mode 100755 index 0000000..4f6b195 --- /dev/null +++ b/src/platform/Tizen/Contact/config.cmake @@ -0,0 +1,55 @@ +get_current_path() + +pkg_search_module(contacts-service REQUIRED contacts-service) +pkg_search_module(pcrecpp REQUIRED libpcrecpp) +pkg_search_module(libdownload-agent REQUIRED libdownload-agent) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_CONTACT + ${contacts-service_INCLUDE_DIRS} + ${pcrecpp_INCLUDE_DIRS} + ${libdownload-agent_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_CONTACT + ${contacts-service_LIBRARIES} + ${pcrecpp_LIBRARIES} + ${libdownload-agent_LIBRARIES} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_CONTACT + ${CURRENT_PATH}/ContactManager.cpp + ${CURRENT_PATH}/AddressBook.cpp + ${CURRENT_PATH}/ContactWrapper.cpp + ${CURRENT_PATH}/ContactSearchEngine.cpp + ${CURRENT_PATH}/ContactFilterValidator.cpp + ${CURRENT_PATH}/query-svc/query-svc.c + ${CURRENT_PATH}/query-svc/query-utility.c +# ${CURRENT_PATH}/../../API/Filesystem/IManager.cpp +# ${CURRENT_PATH}/../../API/Filesystem/IPath.cpp +# ${CURRENT_PATH}/../../API/Filesystem/INode.cpp +# ${CURRENT_PATH}/../../API/Filesystem/IStream.cpp +# ${CURRENT_PATH}/../../API/Filesystem/EventCopy.cpp +# ${CURRENT_PATH}/../../API/Filesystem/EventFind.cpp +# ${CURRENT_PATH}/../../API/Filesystem/EventResolve.cpp +# ${CURRENT_PATH}/../../API/Filesystem/EventMove.cpp +# ${CURRENT_PATH}/../../API/Filesystem/EventRemove.cpp +# ${CURRENT_PATH}/../../API/Filesystem/EventOpen.cpp +# ${CURRENT_PATH}/../../API/Filesystem/EventListNodes.cpp +# ${CURRENT_PATH}/../../API/Filesystem/EventReadText.cpp +# ${CURRENT_PATH}/../../API/Filesystem/NodeFilter.cpp +# ${CURRENT_PATH}/../../API/Filesystem/PathUtils.cpp +# ${CURRENT_PATH}/../Filesystem/System.cpp +# ${CURRENT_PATH}/../Filesystem/Manager.cpp +# ${CURRENT_PATH}/../Filesystem/Utils.cpp +# ${CURRENT_PATH}/../Filesystem/Path.cpp +# ${CURRENT_PATH}/../Filesystem/Node.cpp +# ${CURRENT_PATH}/../Filesystem/Stream.cpp +# ${CURRENT_PATH}/../Filesystem/NodeFilterMatcher.cpp +# ${CURRENT_PATH}/../Filesystem/Command.cpp +# ${CURRENT_PATH}/../Filesystem/MoveCommand.cpp +# ${CURRENT_PATH}/../Filesystem/RemoveCommand.cpp +# ${CURRENT_PATH}/../Filesystem/CopyCommand.cpp + PARENT_SCOPE +) diff --git a/src/platform/Tizen/Contact/query-svc/query-service.h b/src/platform/Tizen/Contact/query-svc/query-service.h new file mode 100755 index 0000000..a3ba85c --- /dev/null +++ b/src/platform/Tizen/Contact/query-svc/query-service.h @@ -0,0 +1,239 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @file query-service.h + * @author JihwaPark (82-32-3016262, jh7979.park@samsung.com) + * @version 1.0(2010.10.05) + * @brief This file is open header file for extern module. + */ + +#ifndef __QUERY_SERVICE_H__ +#define __QUERY_SERVICE_H__ + +#ifndef API +#define API __attribute__ ((visibility("default"))) +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +typedef enum +{ + CONTACT_ID = 0, + + CONTACT_IS_FAVORITE, + CONTACT_RINGTONE, + CONTACT_NOTE, + CONTACT_PHOTO_URI, + CONTACT_LAST_UPDATED_TIME_STAMP, + CONTACT_UID, + + NAME_FIRST = 40, + NAME_MIDDLE, + NAME_LAST, + NAME_PREFIX, + NAME_PHONETIC, + NAME_DISPLAY, + + NICKNAME_NAME = 50, + + NUMBER_ADDRESS = 60, + NUMBER_TYPES, + + EMAIL_ADDRESS = 70, + EMAIL_TYPE, + + URL_ADDRESS = 80, + URL_TYPE, + + ADDRESS_COUNTRY = 90, + ADDRESS_REGION, + ADDRESS_CITY, + ADDRESS_STREET, + ADDRESS_POSTAL_CODE, + ADDRESS_ADDITIONAL, + ADDRESS_TYPE, + + CATEGORY_INFO = 110, + + EVENT_DATE = 120, + EVENT_TYPE, + + ORGANIZATION_NAME = 140, + ORGANIZATION_DEPARTMENT, + ORGANIZATION_TITLE, + ORGANIZATION_ROLE, + + ACCOUNT_ID = 150, + + ATTRIBUTE_MAX = 512 +}contact_attribute_e; + +typedef enum +{ + X_DATA1 = 0, + X_DATA2, + X_DATA3, + X_DATA4, + X_DATA5, + X_DATA6, + X_DATA7, + X_DATA8, + X_DATA9, + X_DATA10, + X_DATA_MAX = 32 +}contact_x_attribute_e; + +typedef enum +{ + AGGREGATED_NAME, + AGGREGATED_RINGTON, + AGGREGATED_PHOTO_URI, + AGGREGATED_IS_FAVORITE, + AGGREGATED_SEND_TO_VOICE_MAIL, + + AGGREGATED_MAX = 100 +}person_delegate_attribute_e; + +typedef enum +{ + EQUAL, + NOT_EQUAL, + GREATER_THAN, + LESS_THAN, + GREATER_THAN_OR_EQUAL, + LESS_THAN_OR_EQUAL, + LIKE, + EXISTS, + CONDITION_MAX +}condition_e; + +typedef enum +{ + LEFT_BRACKET, + RIGHT_BRACKET, + AND, + OR, + CONDITION_TYPE_MAX +}condition_type_e; + +typedef enum +{ + ASC, + DESC +}order_e; + +typedef enum +{ + QUERY_TO_PERSON, + QUERY_TO_CONTACT +}query_type_e; + +typedef enum +{ + SESSION_TYPE_AGGREGATION, + SESSION_TYPE_PRESENCE +}contact_session_type; + +typedef enum +{ + QUERY_DB_LOCK = -17, + QUERY_GROUP_CASE = -16, + QUERY_NORMALIZATION_ERROR = -15, + QUERY_SET_LIMIT = -14, /**< For limit operation */ + QUERY_NO_NEXT_ROW = -13, /**< No Row*/ + QUERY_INSERT_FAIL = -12, + QUERY_ORDERING_FAIL = -11, + QUERY_STATEMENT_FAIL = -10, + QUERY_INVALID_ATTRIBUTE = -9, + QUERY_OVER_MAX_COUNT = -8, /**< memory allocation fail */ + QUERY_OVER_MAX_PROPERTY_CLASS = -7, /**< Invalid property */ + QUERY_NULL_PARAMETER = -6, /**< null input data */ + QUERY_NO_RECORD = -5, /**< No Record */ + QUERY_HANDLE_NONE, /**< No handle */ + QUERY_INVALID_TYPE, /**< invalid value type */ + QUERY_ALLOCATE_MEMORY_FAIL, /**< memory allocation fail */ + QUERY_FAIL = -1, /**< fail */ + QUERY_SUCCESS = 0, /**< no error */ +}query_error; + +typedef struct advanced_handle_t* ADVANCED_HANDLE; /**< query handle value */ + +typedef struct +{ + char* group_name; + int addressbook_id; + int group_id; +}group_info_t; + +/** +* @fn ADVANCED_HANDLE query_init(query_error* error_code) +* This function return QUERY HANDLE body type +* +* @return This function returns value of query handle +* @param[in] handle error code +*/ +API ADVANCED_HANDLE query_init(query_error* error_code, query_type_e contact_type); + +API query_error query_set_attribute(ADVANCED_HANDLE handle, contact_attribute_e attribute); + +API query_error query_get_result_contact(ADVANCED_HANDLE handle); + +API char* query_get_attribute(ADVANCED_HANDLE handle, contact_attribute_e attribute, query_error* error_code); + +API query_error fetch_next_row(ADVANCED_HANDLE handle); + +API query_error query_set_condition(ADVANCED_HANDLE handle, contact_attribute_e attribute, condition_e attr, const char* value); + +API query_error query_set_condition_append(ADVANCED_HANDLE handle, condition_type_e type); + +API query_error query_set_condition_with_indices_begin(ADVANCED_HANDLE handle); + +API query_error query_set_condition_with_indices(ADVANCED_HANDLE handle, const char* contact_index); + +API query_error query_set_condition_with_indices_end(ADVANCED_HANDLE handle); + +API query_error query_set_order_by(ADVANCED_HANDLE handle, contact_attribute_e attribute, order_e ordering); + +API query_error query_finalize(ADVANCED_HANDLE handle); + +API query_error query_set_x_attribute(ADVANCED_HANDLE handle, int cts_custom_type_index, contact_x_attribute_e attribute); + +API query_error query_set_x_condition(ADVANCED_HANDLE handle, int cts_custom_type_index, contact_x_attribute_e attribute, condition_e attr, const char* value); + +API query_error query_next_custom_type(ADVANCED_HANDLE handle); + +API char* query_get_x_attribute(ADVANCED_HANDLE handle, contact_x_attribute_e attribute, int* cts_custom_type_index, query_error* error_code); + + +// Not common APIs +API int get_contact_version(); + +API int find_addressbook_id(int account_id, query_error *error_code); + +API void refresh_addressbook_list(void *data); + +API int* get_all_addressbook_id(int* total_count); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + + +#endif // __QUERY_SERVICE_H__ + diff --git a/src/platform/Tizen/Contact/query-svc/query-svc.c b/src/platform/Tizen/Contact/query-svc/query-svc.c new file mode 100755 index 0000000..0162eee --- /dev/null +++ b/src/platform/Tizen/Contact/query-svc/query-svc.c @@ -0,0 +1,3618 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @file query-svc.h + * @author JihwaPark (82-32-3016262, jh7979.park@samsung.com) + * @version 1.0(2011.10.05) + * @brief This file has filter APIs for supporting advanced query + */ + +#include "query-service.h" +#include "query-type.h" +#include "query-utility.h" +#include +#include + +typedef struct +{ + int addressbook_id; + int account_id; +}addressbook_list; + +GList* g_addressbook_list = NULL; +int total_addressbook_id = 0; + +static int list_cb(CTSvalue *ab, void *user_data) +{ + addressbook_list* list = NULL; + + list = g_new0(addressbook_list, 1); + list->addressbook_id = contacts_svc_value_get_int(ab, CTS_LIST_ADDRESSBOOK_ID_INT); + list->account_id = contacts_svc_value_get_int(ab, CTS_LIST_ADDRESSBOOK_ACC_ID_INT); + + g_addressbook_list = g_list_append(g_addressbook_list, list); + total_addressbook_id++; + + return CTS_SUCCESS; +} + +void __free_addressbook_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_address_list"); + OBJ_FREE(data); +} + +API void refresh_addressbook_list(void *data) +{ + g_list_foreach(g_addressbook_list, __free_addressbook_list, NULL); + g_list_free(g_addressbook_list); + g_addressbook_list = NULL; + + contacts_svc_list_foreach(CTS_LIST_ALL_ADDRESSBOOK, list_cb, NULL); +} + + +API int find_addressbook_id(int account_id, query_error *error_code) +{ + int ret; + int addressbook_id = -1; + + ADVANCED_SVC_TRACE("account_id : %d", account_id); + + if(account_id == 0) + return 0; + + if(g_addressbook_list == NULL) + { + ADVANCED_SVC_TRACE("GENERATE ADDRESSBOOK LIST"); + ret = contacts_svc_list_foreach(CTS_LIST_ALL_ADDRESSBOOK, list_cb, NULL); + } + + GList* tmp_list = g_addressbook_list; + while(tmp_list) + { + addressbook_list* info = (addressbook_list*)tmp_list->data; + if(info->account_id == account_id) + { + addressbook_id = info->addressbook_id; + break; + } + tmp_list = g_list_next(tmp_list); + } + if(addressbook_id == -1) + *error_code = QUERY_NO_RECORD; + else + *error_code = QUERY_SUCCESS; + + ADVANCED_SVC_TRACE("addressbook_id : %d", addressbook_id); + + return addressbook_id; +} + +API int* get_all_addressbook_id(int* total_count) +{ + int i = 0; + int* id_list = NULL; + + if(g_addressbook_list == NULL) + { + ADVANCED_SVC_TRACE("GENERATE ADDRESSBOOK LIST"); + contacts_svc_list_foreach(CTS_LIST_ALL_ADDRESSBOOK, list_cb, NULL); + } + + id_list = g_new0(int, (total_addressbook_id + 2)); + id_list[i] = 0; + + GList* tmp_list = g_addressbook_list; + while(tmp_list) + { + i++; + addressbook_list* info = (addressbook_list*)tmp_list->data; + + id_list[i] = info->addressbook_id; + tmp_list = g_list_next(tmp_list); + } + + *total_count = total_addressbook_id + 1; + + return id_list; +} + +int _value_to_projection(stmt hstmt, char** projection, int count) +{ + int pos = 0; + + pos = count; + + if((*projection) == NULL) + *projection = (char*)g_strdup(_query_column_text(hstmt, pos++)); + else + pos++; + + return pos; +} + +void __convert_number_type_to_str(int db_value, GString* type_str) +{ + if((db_value & HOME) == HOME) + g_string_append_printf (type_str, "%s", number_type_str[1]); + + if((db_value & WORK) == WORK) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", number_type_str[2]); + else + g_string_append_printf(type_str, ",%s", number_type_str[2]); + } + + if((db_value & VOICE) == VOICE) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", number_type_str[3]); + else + g_string_append_printf(type_str, ",%s", number_type_str[3]); + } + + if((db_value & FAX) == FAX) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", number_type_str[4]); + else + g_string_append_printf(type_str, ",%s", number_type_str[4]); + } + + if((db_value & MSG) == MSG) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", number_type_str[5]); + else + g_string_append_printf(type_str, ",%s", number_type_str[5]); + } + + if((db_value & CELL) == CELL) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", number_type_str[6]); + else + g_string_append_printf(type_str, ",%s", number_type_str[6]); + } + + if((db_value & PAGER) == PAGER) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", number_type_str[7]); + else + g_string_append_printf(type_str, ",%s", number_type_str[7]); + } + + if((db_value & BBS) == BBS) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", number_type_str[8]); + else + g_string_append_printf(type_str, ",%s", number_type_str[8]); + } + + if((db_value & MODEM) == MODEM) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", number_type_str[9]); + else + g_string_append_printf(type_str, ",%s", number_type_str[9]); + } + + if((db_value & CAR) == CAR) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", number_type_str[10]); + else + g_string_append_printf(type_str, ",%s", number_type_str[10]); + } + + if((db_value & ISDN) == ISDN) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", number_type_str[11]); + else + g_string_append_printf(type_str, ",%s", number_type_str[11]); + } + + if((db_value & VIDEO) == VIDEO) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", number_type_str[12]); + else + g_string_append_printf(type_str, ",%s", number_type_str[12]); + } + + if((db_value & PCS) == PCS) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", number_type_str[13]); + else + g_string_append_printf(type_str, ",%s", number_type_str[13]); + } + + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", number_type_str[3]); + +} + +void __convert_email_type_to_str(int db_value, GString* type_str) +{ + if((db_value & EMAIL_HOME) == EMAIL_HOME) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", email_type_str[1]); + else + g_string_append_printf (type_str, ",%s", email_type_str[1]); + } + if((db_value & EMAIL_WORK) == EMAIL_WORK) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", email_type_str[2]); + else + g_string_append_printf (type_str, ",%s", email_type_str[2]); + } + + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", email_type_str[1]); +} + +void __convert_url_type_to_str(int db_value, GString* type_str) +{ + if(db_value == URL_HOME) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", url_type_str[URL_HOME]); + else + g_string_append_printf (type_str, ",%s", url_type_str[URL_HOME]); + }else if(db_value == URL_WORK) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", url_type_str[URL_WORK]); + else + g_string_append_printf (type_str, ",%s", url_type_str[URL_WORK]); + } + + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", url_type_str[URL_HOME]); +} + +void __convert_event_type_to_str(int db_value, GString* type_str) +{ + if(db_value == 0) + g_string_append_printf (type_str, "%s", event_type_str[EVENT_BIRTHDAY]); + else if(db_value == 1) + g_string_append_printf (type_str, "%s", event_type_str[EVENT_ANNIVERSARY]); + + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", event_type_str[EVENT_BIRTHDAY]); +} + +void __convert_address_type_to_str(int db_value, GString* type_str) +{ + if((db_value & ADDRESS_TYPE_HOME) == ADDRESS_TYPE_HOME) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", addr_type_str[1]); + else + g_string_append_printf (type_str, ",%s", addr_type_str[1]); + } + if((db_value & ADDRESS_TYPE_WORK) == ADDRESS_TYPE_WORK) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", addr_type_str[2]); + else + g_string_append_printf (type_str, ",%s", addr_type_str[2]); + } + if((db_value & ADDRESS_TYPE_DOM) == ADDRESS_TYPE_DOM) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", addr_type_str[3]); + else + g_string_append_printf (type_str, ",%s", addr_type_str[3]); + } + if((db_value & ADDRESS_TYPE_INTL) == ADDRESS_TYPE_INTL) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", addr_type_str[4]); + else + g_string_append_printf (type_str, ",%s", addr_type_str[4]); + } + if((db_value & ADDRESS_TYPE_POSTAL) == ADDRESS_TYPE_POSTAL) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", addr_type_str[5]); + else + g_string_append_printf (type_str, ",%s", addr_type_str[5]); + } + if((db_value & ADDRESS_TYPE_PARCEL) == ADDRESS_TYPE_PARCEL) + { + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", addr_type_str[6]); + else + g_string_append_printf (type_str, ",%s", addr_type_str[6]); + } + + if(type_str->str[0] == '\0') + g_string_append_printf (type_str, "%s", addr_type_str[1]); +} + +void __convert_x_info_to_str(int db_value, GString* type_str) +{ + g_string_append_printf (type_str, "%d", db_value); +} + +void __convert_is_favorite_to_str(int db_value, GString* type_str) +{ + if(db_value == 1) + g_string_append_printf (type_str, "%s", is_favorite_str[1]); + else + g_string_append_printf (type_str, "%s", is_favorite_str[0]); +} + +int _int_value_to_projection(tables_e table, db_datatype datatype, stmt hstmt, char** projection, int count) +{ + int pos = 0; + int db_value = 0; + GString* type_str = g_string_new (""); + + pos = count; + + if((*projection) == NULL) + { + db_value = _query_column_int(hstmt, pos++); + if(table == DATA_TABLE) + { + switch(datatype) + { + case DB_DATATYPE_NUMBER: + __convert_number_type_to_str(db_value, type_str); + break; + case DB_DATATYPE_EMAIL: + __convert_email_type_to_str(db_value, type_str); + break; + case DB_DATATYPE_URL: + __convert_url_type_to_str(db_value, type_str); + break; + case DB_DATATYPE_EVENT: + __convert_event_type_to_str(db_value, type_str); + break; + case DB_DATATYPE_ADDRESS: + __convert_address_type_to_str(db_value, type_str); + break; + default: + __convert_x_info_to_str(db_value, type_str); + break; + } + }else if(table == CONTACT_TABLE) + { + __convert_is_favorite_to_str(db_value, type_str); + }else if(table == PERSON_TABLE) + { + __convert_is_favorite_to_str(db_value, type_str); + } + + *projection = (char*)g_strdup(type_str->str); + }else + pos++; + + g_string_free(type_str, TRUE); + + return pos; +} + +int _event_value_to_projection(stmt hstmt, char** projection, int count) +{ + int pos = 0; + int db_value = 0; + GString* type_str = g_string_new (""); + + pos = count; + + if((*projection) == NULL) + { + db_value = _query_column_int(hstmt, pos++); + g_string_append_printf (type_str, "%d", db_value); + + *projection = (char*)g_strdup(type_str->str); + }else + pos++; + + g_string_free(type_str, TRUE); + + return pos; +} + +target_table_e _check_join_case(advanced_handle_t* q_handle) +{ + ADVANCED_RETURN_VAL((q_handle->query_table != INVALID_TABLE), {}, INVALID_TABLE_LIST, ("ERROR")); + target_table_e value = INVALID_TABLE_LIST; + + if(strcmp(q_handle->table_list->str, table_key[TABLE_PERSON]) == 0) + { + value = ONLY_PERSON; + }else if(strcmp(q_handle->table_list->str, table_key[TABLE_CONTACT]) == 0) + { + value = ONLY_CONTACT; + }else if(strcmp(q_handle->table_list->str, table_key[TABLE_DATA]) == 0) + { + if(q_handle->query_type == QUERY_TO_CONTACT) + value = ONLY_DATA; + else if(q_handle->query_type == QUERY_TO_PERSON) + value = ONLY_DATA_FROM_PERSON_QUERY; + } + + if(value != INVALID_TABLE_LIST) + return value; + + ADVANCED_SVC_TRACE("!! q_handle->query_table : %d", q_handle->query_table); + + if(((q_handle->query_table & PERSON_TABLE) != 0) && ((q_handle->query_table & CONTACT_TABLE) == 0) && ((q_handle->query_table & DATA_TABLE) != 0)) + { + value = JOIN_PERSON_DATA; + }else if(((q_handle->query_table & PERSON_TABLE) == 0) && ((q_handle->query_table & CONTACT_TABLE) != 0) && ((q_handle->query_table & DATA_TABLE) != 0)) + { + value = JOIN_CONTACT_DATA; + } + + ADVANCED_SVC_TRACE("value is %d", value); + + return value; +} + +query_error _make_contact_info(advanced_handle_t* q_handle, projection_type type, target_table_e join_table) +{ + query_error error_code = QUERY_SUCCESS; + int contact_id = 0; + db_datatype datatype_id = DB_DATATYPE_INVALID; + int count = 0; + char projection[PROJECTION_FIELD_LEN + 1] = {0, }; + + number_t* num_info = NULL; + email_t* email_info = NULL; + url_t* url_info = NULL; + nick_name_t* nick_info = NULL; + address_t* address_info = NULL; + organization_t* organization_info = NULL; + event_info_t* event_info = NULL; + x_info_t* x_info = NULL; + + if(type == ONLY_CONTACT_ID_FIELD) + { + contact_id = _query_column_int(q_handle->hstmt, count++); + }else + { + if(join_table == ONLY_PERSON || join_table == ONLY_CONTACT) + { + contact_id = _query_column_int(q_handle->hstmt, count++); + }else + { + datatype_id = _query_column_int(q_handle->hstmt, count++); + contact_id = _query_column_int(q_handle->hstmt, count++); + } + } + + if(q_handle->window_size > 0) + { + if(q_handle->start_pos >= contact_id) + return QUERY_SUCCESS; + } + + if(q_handle->old_contact_id != contact_id) + { + q_handle->pos++; + q_handle->result_set[q_handle->pos].contact_info = g_new0(contact_t, 1); + q_handle->result_set[q_handle->pos].contact_info->person_info = g_new0(person_contact_t, 1); + q_handle->result_set[q_handle->pos].contact_info->raw_contact_info = g_new0(raw_contact_t, 1); + + if(join_table == ONLY_PERSON || join_table == JOIN_PERSON_DATA) + { + q_handle->result_set[q_handle->pos].contact_info->person_info->contact_id = g_new0(char, 64); + sprintf(q_handle->result_set[q_handle->pos].contact_info->person_info->contact_id, "%d", contact_id); + }else + { + q_handle->result_set[q_handle->pos].contact_info->raw_contact_info->contact_id = g_new0(char, 64); + sprintf(q_handle->result_set[q_handle->pos].contact_info->raw_contact_info->contact_id, "%d", contact_id); + } + + q_handle->result_set[q_handle->pos].is_occupied = true; + q_handle->old_contact_id = contact_id; + + q_handle->mapping_id_to_result_set[q_handle->pos].contact_id = contact_id; + q_handle->total_result_set_count++; + } + + if((q_handle->window_size > 0) && (q_handle->total_result_set_count > q_handle->window_size)) + { + q_handle->total_result_set_count--; + return QUERY_SET_LIMIT; + } + + switch(datatype_id) + { + case DB_DATATYPE_NAME : + { + ADVANCED_RETURN_VAL((q_handle->result_set[q_handle->pos].contact_info->name_info == NULL), {}, QUERY_FAIL, ("ONLY ONE NAME IS POSSIBLE")); + q_handle->result_set[q_handle->pos].contact_info->name_info = g_new0(name_t, 1); + ADVANCED_CATCH_SET_ERROR((q_handle->result_set[q_handle->pos].contact_info->name_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + } + break; + case DB_DATATYPE_NUMBER: + { + num_info = g_new0(number_t, 1); + ADVANCED_CATCH_SET_ERROR((num_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + } + break; + case DB_DATATYPE_EMAIL: + { + email_info = g_new0(email_t, 1); + ADVANCED_CATCH_SET_ERROR((email_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + } + break; + case DB_DATATYPE_URL: + { + url_info = g_new0(url_t, 1); + ADVANCED_CATCH_SET_ERROR((url_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + } + break; + case DB_DATATYPE_NICK_NAME: + { + nick_info = g_new0(nick_name_t, 1); + ADVANCED_CATCH_SET_ERROR((nick_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + } + break; + case DB_DATATYPE_ADDRESS: + { + address_info = g_new0(address_t, 1); + ADVANCED_CATCH_SET_ERROR((address_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + } + break; + case DB_DATATYPE_ORGANIZATION: + { + organization_info = g_new0(organization_t, 1); + ADVANCED_CATCH_SET_ERROR((organization_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + } + break; + case DB_DATATYPE_EVENT: + { + event_info = g_new0(event_info_t, 1); + ADVANCED_CATCH_SET_ERROR((event_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + } + break; + default: + { + if(datatype_id > DB_DATATYPE_MAX) + { + x_info = g_new0(x_info_t, 1); + ADVANCED_CATCH_SET_ERROR((x_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + } + } + break; + } + + int old_count = 0; + GList* tmp_projection = q_handle->new_projection; + while(tmp_projection) + { + projection_t* projection_info = (projection_t*)tmp_projection->data; + memset(projection, 0x00, sizeof(projection)); + + snprintf(projection, sizeof(projection) - 1, "%s", projection_info->field); + + tmp_projection = g_list_next(tmp_projection); + + old_count = count; + switch(datatype_id) + { + case DB_DATATYPE_NAME : + { + if(strcmp(field_key[FIELD_DATA2], projection) == 0 && q_handle->attribute_list[NAME_FIRST] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->name_info->first_name), count); + }else if(strcmp(field_key[FIELD_DATA4], projection) == 0 && q_handle->attribute_list[NAME_MIDDLE] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->name_info->middle_name), count); + }else if(strcmp(field_key[FIELD_DATA3], projection) == 0 && q_handle->attribute_list[NAME_LAST] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->name_info->last_name), count); + }else if(strcmp(field_key[FIELD_DATA6], projection) == 0 && q_handle->attribute_list[NAME_PREFIX] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->name_info->prefix), count); + }else if(strcmp(field_key[FIELD_DATA7], projection) == 0 && q_handle->attribute_list[NAME_PHONETIC] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->name_info->phonetic_name), count); + }else if(strcmp(field_key[FIELD_DATA5], projection) == 0 && q_handle->attribute_list[NAME_DISPLAY] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->name_info->display_name), count); + } + + } + break; + case DB_DATATYPE_NUMBER: + { + if(strcmp(field_key[FIELD_DATA2], projection) == 0 && q_handle->attribute_list[NUMBER_ADDRESS] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(num_info->number), count); + }else if(strcmp(field_key[FIELD_DATA1], projection) == 0 && q_handle->attribute_list[NUMBER_TYPES] == 1) + { + count = _int_value_to_projection(DATA_TABLE, DB_DATATYPE_NUMBER, q_handle->hstmt, &(num_info->number_type), count); + } + } + break; + case DB_DATATYPE_EMAIL: + { + if(strcmp(field_key[FIELD_DATA2], projection) == 0 && q_handle->attribute_list[EMAIL_ADDRESS] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(email_info->email_addr), count); + }else if(strcmp(field_key[FIELD_DATA1], projection) == 0 && q_handle->attribute_list[EMAIL_TYPE] == 1) + { + count = _int_value_to_projection(DATA_TABLE, DB_DATATYPE_EMAIL, q_handle->hstmt, &(email_info->email_type), count); + } + + } + break; + case DB_DATATYPE_URL: + { + if(strcmp(field_key[FIELD_DATA2], projection) == 0 && q_handle->attribute_list[URL_ADDRESS] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(url_info->url_addr), count); + }else if(strcmp(field_key[FIELD_DATA1], projection) == 0 && q_handle->attribute_list[URL_TYPE] == 1) + { + count = _int_value_to_projection(DATA_TABLE, DB_DATATYPE_URL, q_handle->hstmt, &(url_info->url_type), count); + } + } + break; + case DB_DATATYPE_NICK_NAME: + { + if(strcmp(field_key[FIELD_DATA2], projection) == 0 && q_handle->attribute_list[NICKNAME_NAME] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(nick_info->nick_name), count); + } + } + break; + case DB_DATATYPE_ADDRESS: + { + if(strcmp(field_key[FIELD_DATA8], projection) == 0 && q_handle->attribute_list[ADDRESS_COUNTRY] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(address_info->country), count); + }else if(strcmp(field_key[FIELD_DATA4], projection) == 0 && q_handle->attribute_list[ADDRESS_REGION] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(address_info->region), count); + }else if(strcmp(field_key[FIELD_DATA5], projection) == 0 && q_handle->attribute_list[ADDRESS_CITY] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(address_info->city), count); + }else if(strcmp(field_key[FIELD_DATA6], projection) == 0 && q_handle->attribute_list[ADDRESS_STREET] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(address_info->street), count); + }else if(strcmp(field_key[FIELD_DATA3], projection) == 0 && q_handle->attribute_list[ADDRESS_POSTAL_CODE] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(address_info->postal_code), count); + }else if(strcmp(field_key[FIELD_DATA7], projection) == 0 && q_handle->attribute_list[ADDRESS_ADDITIONAL] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(address_info->addtional), count); + }else if(strcmp(field_key[FIELD_DATA1], projection) == 0 && q_handle->attribute_list[ADDRESS_TYPE] == 1) + { + count = _int_value_to_projection(DATA_TABLE, DB_DATATYPE_ADDRESS, q_handle->hstmt, &(address_info->type), count); + } + } + break; + case DB_DATATYPE_ORGANIZATION: + { + if(strcmp(field_key[FIELD_DATA2], projection) == 0 && q_handle->attribute_list[ORGANIZATION_NAME] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(organization_info->organization_name), count); + }else if(strcmp(field_key[FIELD_DATA3], projection) == 0 && q_handle->attribute_list[ORGANIZATION_DEPARTMENT] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(organization_info->department), count); + }else if(strcmp(field_key[FIELD_DATA4], projection) == 0 && q_handle->attribute_list[ORGANIZATION_TITLE] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(organization_info->title), count); + }else if(strcmp(field_key[FIELD_DATA5], projection) == 0 && q_handle->attribute_list[ORGANIZATION_ROLE] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(organization_info->role), count); + } + } + break; + case DB_DATATYPE_EVENT: + { + if(strcmp(field_key[FIELD_DATA1], projection) == 0 && q_handle->attribute_list[EVENT_TYPE] == 1) + { + count = _int_value_to_projection(DATA_TABLE, DB_DATATYPE_EVENT, q_handle->hstmt, &(event_info->type), count); + }else if(strcmp(field_key[FIELD_DATA2], projection) == 0 && q_handle->attribute_list[EVENT_DATE] == 1) + { + count = _event_value_to_projection(q_handle->hstmt, &(event_info->date), count); + } + } + break; + default: + { + if(datatype_id > DB_DATATYPE_MAX) + { + if(strcmp(field_key[FIELD_DATA1], projection) == 0 && q_handle->x_attribute_list[X_DATA1] == 1) + { + count = _int_value_to_projection(DATA_TABLE, datatype_id, q_handle->hstmt, &(x_info->data1), count); + }else if(strcmp(field_key[FIELD_DATA2], projection) == 0 && q_handle->x_attribute_list[X_DATA2] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(x_info->data2), count); + }else if(strcmp(field_key[FIELD_DATA3], projection) == 0 && q_handle->x_attribute_list[X_DATA3] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(x_info->data3), count); + }else if(strcmp(field_key[FIELD_DATA4], projection) == 0 && q_handle->x_attribute_list[X_DATA4] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(x_info->data4), count); + }else if(strcmp(field_key[FIELD_DATA5], projection) == 0 && q_handle->x_attribute_list[X_DATA5] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(x_info->data5), count); + }else if(strcmp(field_key[FIELD_DATA6], projection) == 0 && q_handle->x_attribute_list[X_DATA6] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(x_info->data6), count); + }else if(strcmp(field_key[FIELD_DATA7], projection) == 0 && q_handle->x_attribute_list[X_DATA7] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(x_info->data7), count); + }else if(strcmp(field_key[FIELD_DATA8], projection) == 0 && q_handle->x_attribute_list[X_DATA8] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(x_info->data8), count); + }else if(strcmp(field_key[FIELD_DATA9], projection) == 0 && q_handle->x_attribute_list[X_DATA9] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(x_info->data9), count); + }else if(strcmp(field_key[FIELD_DATA10], projection) == 0 && q_handle->x_attribute_list[X_DATA10] == 1) + { + count = _value_to_projection(q_handle->hstmt, &(x_info->data10), count); + } + } + } + break; + } + + { + if(join_table == ONLY_PERSON || join_table == JOIN_PERSON_DATA) + { + if(strcmp(field_key[FIELD_PERSON_IS_SELF], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->is_self), count); + else if(strcmp(field_key[FIELD_CONTACT_ID_FOR_NAME], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->contact_id_for_name), count); + else if(strcmp(field_key[FIELD_CONTACT_ID_FOR_PHOTO], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->contact_id_for_photo), count); + else if(strcmp(field_key[FIELD_CONTACT_ID_FOR_RINGTONE], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->contactid_for_ringtone), count); + else if(strcmp(field_key[FIELD_PERSON_PREFIX_NAME], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->prefix), count); + else if(strcmp(field_key[FIELD_PERSON_FIRST_NAME], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->first_name), count); + else if(strcmp(field_key[FIELD_PERSON_MIDDLE_NAME], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->middle_name), count); + else if(strcmp(field_key[FIELD_PERSON_LAST_NAME], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->last_name), count); + else if(strcmp(field_key[FIELD_PERSON_PHONETIC_NAME], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->phonetic_name), count); + else if(strcmp(field_key[FIELD_PERSON_DISPLAY_NAME], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->display_name), count); + else if(strcmp(field_key[FIELD_PERSON_PHOTO_URI], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->photo_URI), count); + else if(strcmp(field_key[FIELD_PERSON_LAST_UPDATED_TIME], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->last_updated_timestamp), count); + else if(strcmp(field_key[FIELD_PERSON_IS_FAVORITE], projection) == 0) + count = _int_value_to_projection(PERSON_TABLE, DB_DATATYPE_INVALID, q_handle->hstmt, + &(q_handle->result_set[q_handle->pos].contact_info->person_info->is_favorite), count); + else if(strcmp(field_key[FIELD_PERSON_SEND_TO_VOICEMAIL], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->send_to_voicemail), count); + else if(strcmp(field_key[FIELD_PERSON_RINGTONE], projection) == 0) + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->person_info->ringtone), count); + }else + { + if(strcmp(field_key[FIELD_RINGTONE], projection) == 0) + { + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->raw_contact_info->ringtone), count); + }else if(strcmp(field_key[FIELD_NOTE], projection) == 0) + { + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->raw_contact_info->note), count); + }else if(strcmp(field_key[FIELD_IS_FAVORITE], projection) == 0) + { + count = _int_value_to_projection(CONTACT_TABLE, DB_DATATYPE_INVALID, q_handle->hstmt, + &(q_handle->result_set[q_handle->pos].contact_info->raw_contact_info->is_favorite), count); + }else if(strcmp(field_key[FIELD_CHANGED_TIME], projection) == 0) + { + int changed_time = 0; + char tmp_string[64] = {0, }; + changed_time = _query_column_int(q_handle->hstmt, count++); + sprintf(tmp_string, "%d", changed_time); + q_handle->result_set[q_handle->pos].contact_info->raw_contact_info->last_updated_time_stamp = (char*)g_strdup(tmp_string); + }else if(strcmp(field_key[FIELD_CONTACT_ACCOUNT_ID], projection) == 0) + { + int db_value = _query_column_int(q_handle->hstmt, count++); + if(db_value != 0) + { + q_handle->result_set[q_handle->pos].contact_info->raw_contact_info->account_id = g_new0(char, 64); + sprintf(q_handle->result_set[q_handle->pos].contact_info->raw_contact_info->account_id, "%d", db_value); + } + }else if(strcmp(field_key[FIELD_UID], projection) == 0) + { + count = _value_to_projection(q_handle->hstmt, &(q_handle->result_set[q_handle->pos].contact_info->raw_contact_info->uid), count); + } + } + } + if(count == old_count) + count++; + } + + switch(datatype_id) + { + case DB_DATATYPE_NUMBER: + q_handle->result_set[q_handle->pos].contact_info->number_list = g_list_append(q_handle->result_set[q_handle->pos].contact_info->number_list, num_info); + break; + case DB_DATATYPE_EMAIL: + q_handle->result_set[q_handle->pos].contact_info->email_list = g_list_append(q_handle->result_set[q_handle->pos].contact_info->email_list, email_info); + break; + case DB_DATATYPE_URL: + q_handle->result_set[q_handle->pos].contact_info->url_list = g_list_append(q_handle->result_set[q_handle->pos].contact_info->url_list, url_info); + break; + case DB_DATATYPE_NICK_NAME : + q_handle->result_set[q_handle->pos].contact_info->nickname_list = g_list_append(q_handle->result_set[q_handle->pos].contact_info->nickname_list, nick_info); + break; + case DB_DATATYPE_ADDRESS : + q_handle->result_set[q_handle->pos].contact_info->address_list = g_list_append(q_handle->result_set[q_handle->pos].contact_info->address_list, address_info); + break; + case DB_DATATYPE_ORGANIZATION : + q_handle->result_set[q_handle->pos].contact_info->organization_list = g_list_append(q_handle->result_set[q_handle->pos].contact_info->organization_list, organization_info); + break; + case DB_DATATYPE_EVENT : + q_handle->result_set[q_handle->pos].contact_info->event_list = g_list_append(q_handle->result_set[q_handle->pos].contact_info->event_list, event_info); + break; + default: + { + if(datatype_id > DB_DATATYPE_MAX) + { + x_info->datatype_id = datatype_id; + ADVANCED_SVC_TRACE("x_info->datatype_id : %d", x_info->datatype_id); + q_handle->result_set[q_handle->pos].contact_info->x_list = g_list_append(q_handle->result_set[q_handle->pos].contact_info->x_list, x_info); + } + } + break; + } +CATCH: + return error_code; +} + +API ADVANCED_HANDLE query_init(query_error* error_code, query_type_e query_type) +{ + ADVANCED_RETURN_VAL((query_type >= QUERY_TO_PERSON), {}, NULL, ("INVALID QUERY TYPE")); + + advanced_handle_t* handle = NULL; + handle = g_new0(advanced_handle_t, 1); + ADVANCED_CATCH_SET_ERROR_POINTER((handle != NULL), {}, QUERY_HANDLE_NONE, ("ALLOCATION FAIL")); + + *error_code = _db_init(); + ADVANCED_CATCH_SET_ERROR_POINTER((*error_code == QUERY_SUCCESS), {}, QUERY_STATEMENT_FAIL, ("DATABASE INIT FAIL")); + + handle->pos = -1; + handle->query_type = query_type; + + handle->condition_text = g_string_new (""); + handle->table_list = g_string_new (""); + handle->order = g_string_new (""); + handle->use_normal_field_key = g_string_new (""); + handle->use_contact_table_id = g_string_new (""); + handle->optimize_condition = true; + handle->id_list = g_string_new (""); + + ADVANCED_SVC_TRACE("QUERY INIT SUCCESS"); + +CATCH: + if(*error_code != QUERY_SUCCESS) + { + _free_handle_info(handle); + handle = NULL; + } + + return (ADVANCED_HANDLE)handle; +} + +query_error _check_extra_contact_info(advanced_handle_t* q_handle, extra_info_type type, contact_attribute_e attribute) +{ + query_error error_code = QUERY_FAIL; + + if(type == EXTRA_INFO_TYPE_FIELD) + { + if(attribute == CONTACT_PHOTO_URI) + { + q_handle->extra_info = q_handle->extra_info | CONTACT_PHOTO; + error_code = QUERY_SUCCESS; + }else if(attribute == CATEGORY_INFO) + { + q_handle->extra_info = q_handle->extra_info | CATEGORIES; + error_code = QUERY_SUCCESS; + } + }else if(type == EXTRA_INFO_TYPE_CONDITION) + { + if(attribute == CONTACT_PHOTO_URI) + { + q_handle->condition_extra_info = q_handle->condition_extra_info | CONTACT_PHOTO; + error_code = QUERY_SUCCESS; + }else if(attribute == CATEGORY_INFO) + { + q_handle->condition_extra_info = q_handle->condition_extra_info | CATEGORIES; + error_code = QUERY_SUCCESS; + } + } + + return error_code; +} + +API query_error query_set_attribute(ADVANCED_HANDLE handle, contact_attribute_e attribute) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + ADVANCED_RETURN_VAL((attribute < ATTRIBUTE_MAX), {}, QUERY_INVALID_ATTRIBUTE, ("INVALID CONTACT ATTRIBUTE")); + + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + + char* column_name = NULL; + char* table_name = NULL; + query_error error_code = QUERY_SUCCESS; + char* loc = NULL; + projection_t* projection_info = NULL; + + ADVANCED_SVC_TRACE("attribute : %d", attribute); + q_handle->attribute_list[attribute] = 1; + + error_code = _check_extra_contact_info(q_handle, EXTRA_INFO_TYPE_FIELD, attribute); + if(error_code == QUERY_SUCCESS) + attribute = CONTACT_ID; + error_code = QUERY_SUCCESS; + + if(q_handle->query_type == QUERY_TO_PERSON) + { + column_name = _convert_person_attribute_to_column_name(attribute); + if(column_name != NULL) + q_handle->person_field = attribute; + } + + if(column_name == NULL) + column_name = _convert_attribute_to_column_name(attribute); + + projection_info = g_new0(projection_t, 1); + projection_info->field = g_strdup(column_name); + q_handle->projection = g_list_append(q_handle->projection, projection_info); + + if(q_handle->query_type == QUERY_TO_PERSON) + table_name = _convert_person_attribute_to_table_name(attribute); + + if((attribute > CONTACT_LAST_UPDATED_TIME_STAMP) && (table_name == NULL)) + { + error_code = _set_datatype_list(q_handle, attribute); + ADVANCED_CATCH_SET_ERROR((error_code == QUERY_SUCCESS), {}, QUERY_FAIL, ("DATA_TYPE CONVERTING FAIL")); + } + + if(table_name == NULL) + table_name = _convert_attribute_to_table_name(attribute); + + if(q_handle->table_list->str[0] != '\0') + { + loc = strstr(q_handle->table_list->str, table_name); + if(loc == NULL) + g_string_append_printf(q_handle->table_list, ", %s", table_name); + } + else + { + g_string_append_printf(q_handle->table_list, "%s", table_name); + } + + tables_e table_type = _contact_table_name_to_table_type(table_name); + q_handle->query_table = q_handle->query_table | table_type; + + ADVANCED_SVC_TRACE("table list : %s", q_handle->table_list->str); + +CATCH: + return error_code; +} + +query_error _construct_order_query(advanced_handle_t* q_handle, GString* query, target_table_e join_table) +{ + predefine_datatype datatype = DATATYPE_INVALID; + db_datatype db_datatype_id = DB_DATATYPE_NAME; + query_error error_code = QUERY_SUCCESS; + + datatype = _convert_attribute_to_mimetype_id(q_handle->order_field); + db_datatype_id = _convert_datatype_to_db_type(datatype); + + if(q_handle->query_type == QUERY_TO_CONTACT) + { + switch(join_table) + { + case ONLY_CONTACT : + { + g_string_printf (query, "select distinct(%s) from %s order by %s", field_key[FIELD_CONTACT_CONTACT_ID], table_key[TABLE_CONTACT], q_handle->order->str); + } + break; + case ONLY_DATA : + case JOIN_CONTACT_DATA : + { + if(db_datatype_id == DB_DATATYPE_INVALID) + { + g_string_printf (query, "select distinct(%s) from %s order by %s", field_key[FIELD_DATA_CONTACT_ID], table_key[TABLE_DATA], q_handle->order->str); + }else + { + g_string_printf (query, "select distinct(%s) from %s where %s = %d order by %s", + field_key[FIELD_DATA_CONTACT_ID], table_key[TABLE_DATA], field_key[FIELD_DATA_DATATYPE_ID], db_datatype_id, q_handle->order->str); + } + } + break; + default: + break; + } + }else + { + switch(join_table) + { + case ONLY_PERSON : + { + g_string_printf (query, "select distinct(%s) from %s order by %s", field_key[FIELD_PERSON_CONTACT_ID], table_key[TABLE_PERSON], q_handle->order->str); + } + break; + case ONLY_DATA_FROM_PERSON_QUERY : + case JOIN_PERSON_DATA : + { + if(db_datatype_id == DB_DATATYPE_INVALID) + { + g_string_printf (query, "select distinct(%s) from %s order by %s", field_key[FIELD_DATA_PERSON_ID], table_key[TABLE_DATA], q_handle->order->str); + }else + { + g_string_printf (query, "select distinct(%s) from %s where %s = %d order by %s", + field_key[FIELD_DATA_PERSON_ID], table_key[TABLE_DATA], field_key[FIELD_DATA_DATATYPE_ID], db_datatype_id, q_handle->order->str); + } + } + break; + default: + break; + } + } + ADVANCED_CATCH_SET_ERROR(query->str[0] != '\0', {}, QUERY_INVALID_ATTRIBUTE, ("DO NOT SUPPORT CASE")); + +CATCH: + return error_code; +} + +int _make_order_list(advanced_handle_t* q_handle, int count, target_table_e join_table) +{ + ADVANCED_RETURN_VAL((q_handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + ADVANCED_RETURN_VAL((q_handle->order->str[0] != '\0'), {}, QUERY_NULL_PARAMETER, ("NO ORDER STRING")); + + GString* query; + int rc = -1; + int order_pos = 0; + int i = 0; + int j = 0; + query_error error_code = QUERY_SUCCESS; + + ADVANCED_SVC_TRACE("q_handle->order : %s", q_handle->order->str); + query = g_string_new (""); + + if(q_handle->limit_iter == true) + { + q_handle->ordering_list = g_new0(ordering_list_t, q_handle->total_result_set_count); + ADVANCED_CATCH_SET_ERROR((q_handle->ordering_list != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + for(j=0; jtotal_count; j++) + { + if(order_pos >= q_handle->total_result_set_count) + break; + + int high, low; + + high = q_handle->total_result_set_count; + low = 0; + + while(high >= low) + { + i = ( low + high ) / 2; + + if(q_handle->mapping_id_to_result_set[i].contact_id > q_handle->full_ordered_contact_id[j].contact_id) + high = i - 1; + else if(q_handle->mapping_id_to_result_set[i].contact_id < q_handle->full_ordered_contact_id[j].contact_id) + low = i + 1; + else if(q_handle->mapping_id_to_result_set[i].contact_id == q_handle->full_ordered_contact_id[j].contact_id) + { + q_handle->ordering_list[order_pos].ordered_pos = i; + order_pos++; + break; + } + } + } + }else + { + error_code = _construct_order_query(q_handle, query, join_table); + ADVANCED_CATCH_SET_ERROR(error_code == QUERY_SUCCESS, {}, error_code, ("QUERY CONSTRUCTION FAIL")); + + q_handle->full_ordered_contact_id = g_new0(mapping_list_t, count); + ADVANCED_CATCH_SET_ERROR((q_handle->full_ordered_contact_id != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + q_handle->ordering_list = g_new0(ordering_list_t, q_handle->total_result_set_count); + ADVANCED_CATCH_SET_ERROR((q_handle->ordering_list != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + q_handle->hstmt = _query_prepare(query->str); + ADVANCED_CATCH_SET_ERROR((q_handle->hstmt != NULL), {}, QUERY_STATEMENT_FAIL, ("database prepare fail")); + + rc = _query_step(q_handle->hstmt); + ADVANCED_CATCH_SET_ERROR((rc == SQLITE_ROW), {}, QUERY_ORDERING_FAIL, ("No record in database")); + + while(rc == SQLITE_ROW) + { + if(q_handle->total_count >= count) + break; + + q_handle->full_ordered_contact_id[q_handle->total_count].contact_id = _query_column_int(q_handle->hstmt, 0); + rc = _query_step(q_handle->hstmt); + q_handle->total_count++; + } + q_handle->total_count = count; + _query_finalize(q_handle->hstmt); + + for(j=0; jtotal_count; j++) + { + if(order_pos >= q_handle->total_result_set_count) + break; + + if(q_handle->full_ordered_contact_id[j].contact_id <= q_handle->mapping_id_to_result_set[q_handle->total_result_set_count - 1].contact_id) + { + int high, low; + + high = q_handle->total_result_set_count; + low = 0; + + while(high >= low) + { + i = ( low + high ) / 2; + + if(q_handle->mapping_id_to_result_set[i].contact_id > q_handle->full_ordered_contact_id[j].contact_id) + high = i - 1; + else if(q_handle->mapping_id_to_result_set[i].contact_id < q_handle->full_ordered_contact_id[j].contact_id) + low = i + 1; + else if(q_handle->mapping_id_to_result_set[i].contact_id == q_handle->full_ordered_contact_id[j].contact_id) + { + q_handle->ordering_list[order_pos].ordered_pos = i; + order_pos++; + break; + } + } + } + } + } + q_handle->return_array_pos = q_handle->ordering_list[0].ordered_pos; + q_handle->pos = 0; + +CATCH: + g_string_free (query, TRUE); + return error_code; +} + +query_error _make_contact_id_list_by_condition_part(advanced_handle_t* q_handle, int count, GString* sub_query) +{ + ADVANCED_RETURN_VAL((q_handle->condition_text->str[0] != '\0'), {}, QUERY_SUCCESS, ("NO CONDITION PART")); + + query_error error_code = QUERY_SUCCESS; + alias_key_e alias = ALIAS_A; + alias_key_e data_table_alias = ALIAS_INVALID; + char* id_field = NULL; + char* default_id_field = NULL; + alias_key_e default_alias = ALIAS_INVALID; + + GString* tmp_query; + tmp_query = g_string_new(""); + + ADVANCED_SVC_TRACE("CHECK CONDITION PART !! "); + + GList* tmp_table = q_handle->condition_table_list; + while(tmp_table) + { + condition_table_t* table_info = (condition_table_t*)tmp_table->data; + + if(strcmp(table_info->table, table_key[TABLE_PERSON]) == 0) + id_field = condition_field_key[FIELD_PERSON_CONTACT_ID]; + else if(strcmp(table_info->table, table_key[TABLE_CONTACT]) == 0) + id_field = condition_field_key[FIELD_CONTACT_CONTACT_ID]; + else if(strcmp(table_info->table, table_key[TABLE_DATA]) == 0) + { + if(q_handle->query_type == QUERY_TO_PERSON) + id_field = condition_field_key[FIELD_DATA_PERSON_ID]; + else + id_field = condition_field_key[FIELD_DATA_CONTACT_ID]; + + if(data_table_alias == ALIAS_INVALID) + data_table_alias = table_info->alias; + } + + if(q_handle->optimize_condition == true) + { + if(sub_query->str[0] == '\0') + { + g_string_append_printf (sub_query, "select distinct(%s.%s) from %s %s", + alias_key[table_info->alias], id_field, table_info->table, alias_key[table_info->alias]); + default_id_field = id_field; + default_alias = table_info->alias; + } + }else + { + if(sub_query->str[0] == '\0') + { + g_string_append_printf (sub_query, "select distinct(%s.%s) from %s %s", + alias_key[table_info->alias], id_field, table_info->table, alias_key[table_info->alias]); + default_id_field = id_field; + default_alias = table_info->alias; + }else + g_string_append_printf (sub_query, ", %s %s", table_info->table, alias_key[table_info->alias]); + + if(alias != table_info->alias) + g_string_append_printf (tmp_query, " (%s.%s = %s.%s) and", alias_key[default_alias], default_id_field, alias_key[table_info->alias], id_field); + } + + alias = table_info->alias; + tmp_table = g_list_next(tmp_table); + } + + g_string_append_printf (sub_query, " where"); + + if(tmp_query->str[0] != '\0') + g_string_append_printf (sub_query, " %s", tmp_query->str); + + if(q_handle->optimize_condition && q_handle->condition_list && q_handle->current_alias > ALIAS_A) + { + GList* tmp_condition = q_handle->condition_list; + bool is_first = true; + while(tmp_condition) + { + condition_list_t* condition_info = (condition_list_t*)tmp_condition->data; + + if(is_first) + { + g_string_append_printf(sub_query, " (%s.id in (select id from %s where %s %s ? and %s = %d", + alias_key[data_table_alias], table_key[TABLE_DATA], condition_info->column_name, + condition_info->condition, condition_field_key[FIELD_DATA_DATATYPE_ID], condition_info->datatype); + is_first = false; + }else + { + g_string_append_printf(sub_query, " union select id from %s where %s %s ? and %s = %d", + table_key[TABLE_DATA], condition_info->column_name, + condition_info->condition, condition_field_key[FIELD_DATA_DATATYPE_ID], condition_info->datatype); + } + + tmp_condition = g_list_next(tmp_condition); + } + g_string_append_printf(sub_query, " ))"); + + }else + g_string_append_printf (sub_query, " (%s)", q_handle->condition_text->str); + + g_string_free (tmp_query, TRUE); + return error_code; +} + +void _construct_query(target_table_e value, advanced_handle_t* q_handle, GString* query, char* condtion_sub_query, projection_type type) +{ + GString* condition; + GString* contact_condition; + bool is_first = true; + bool use_sub_query = true; + + condition = g_string_new(""); + contact_condition = g_string_new(""); + + if(q_handle->condition_datatype == DATATYPE_INVALID && q_handle->condition_category == NULL) + use_sub_query = false; + + GList* tmp_datatype_list = q_handle->datatype_list; + while(tmp_datatype_list) + { + datatype_t* datatype_info = (datatype_t*)tmp_datatype_list->data; + + if(is_first) + g_string_append_printf(condition, "%s = %d", datatype_info->field, datatype_info->datatype); + else + g_string_append_printf(condition, " or %s = %d", datatype_info->field, datatype_info->datatype); + + tmp_datatype_list = g_list_next(tmp_datatype_list); + is_first = false; + } + + switch(value) + { + case ONLY_CONTACT: + { + g_string_append_printf(query, "select %s from %s", q_handle->query_string, table_key[TABLE_CONTACT]); + + if(strlen(condtion_sub_query) != 0) + { + if(use_sub_query == false) + { + g_string_append_printf(query, " where %s", q_handle->use_contact_table_id->str); + }else + g_string_append_printf(query, " where %s in (%s)", field_key[FIELD_CONTACT_CONTACT_ID], condtion_sub_query); + } + + if(q_handle->order->str[0] != '\0') + g_string_append_printf(query, " order by %s", q_handle->order->str); + else + g_string_append_printf(query, " order by %s", field_key[FIELD_CONTACT_CONTACT_ID]); + } + break; + case ONLY_PERSON: + { + g_string_append_printf(query, "select %s from %s", q_handle->query_string, table_key[TABLE_PERSON]); + + if(strlen(condtion_sub_query) != 0) + g_string_append_printf(query, " where %s in (%s)", field_key[FIELD_PERSON_CONTACT_ID], condtion_sub_query); + + if(q_handle->order->str[0] != '\0') + g_string_append_printf(query, " order by %s", q_handle->order->str); + else + g_string_append_printf(query, " order by %s", field_key[FIELD_PERSON_CONTACT_ID]); + } + break; + case ONLY_DATA: + { + if(type == ONLY_CONTACT_ID_FIELD) + g_string_append_printf(query, "select %s from %s", q_handle->query_string, table_key[TABLE_DATA]); + else + g_string_append_printf(query, "select %s, %s from %s", field_key[FIELD_DATA_DATATYPE_ID], q_handle->query_string, table_key[TABLE_DATA]); + + if(strlen(condtion_sub_query) != 0) + { + if(use_sub_query == false) + g_string_append_printf(query, " where %s", q_handle->use_normal_field_key->str); + else + g_string_append_printf(query, " where %s in (%s) and (%s)", field_key[FIELD_DATA_CONTACT_ID], condtion_sub_query, condition->str); + } + else + g_string_append_printf(query, " where (%s)", condition->str); + + g_string_append_printf(query, " order by %s", field_key[FIELD_DATA_CONTACT_ID]); + + } + break; + case ONLY_DATA_FROM_PERSON_QUERY: + { + if(type == ONLY_CONTACT_ID_FIELD) + g_string_append_printf(query, "select %s from %s", q_handle->query_string, table_key[TABLE_DATA]); + else + g_string_append_printf(query, "select %s, %s from %s", field_key[FIELD_DATA_DATATYPE_ID], q_handle->query_string, table_key[TABLE_DATA]); + + if(strlen(condtion_sub_query) != 0) + { + if(use_sub_query == false) + g_string_append_printf(query, " where %s = ?", field_key[FIELD_PERSON_CONTACT_ID]); + else + g_string_append_printf(query, " where %s in (%s)", field_key[FIELD_PERSON_CONTACT_ID], condtion_sub_query); + } + + if(strlen(condtion_sub_query) != 0) + g_string_append_printf(query, " and (%s)", condition->str); + else + g_string_append_printf(query, " where (%s)", condition->str); + + g_string_append_printf(query, " order by %s", field_key[FIELD_PERSON_CONTACT_ID]); + + } + break; + case JOIN_CONTACT_DATA: + { + g_string_append_printf(query, "select %s, %s from %s, %s", field_key[FIELD_DATA_DATATYPE_ID], q_handle->query_string, table_key[TABLE_CONTACT], table_key[TABLE_DATA]); + g_string_append_printf(query, " where (%s = %s) and", field_key[FIELD_CONTACT_CONTACT_ID], field_key[FIELD_DATA_CONTACT_ID]); + + if(strlen(condtion_sub_query) != 0) + { + if(use_sub_query == false) + g_string_append_printf(query, " %s and", q_handle->use_normal_field_key->str); + else + g_string_append_printf(query, " %s in (%s) and", field_key[FIELD_CONTACT_CONTACT_ID], condtion_sub_query); + } + g_string_append_printf(query, " (%s) order by %s", condition->str, field_key[FIELD_CONTACT_CONTACT_ID]); + + } + break; + case JOIN_PERSON_DATA: + { + g_string_append_printf(query, "select %s, %s from %s, %s", field_key[FIELD_DATA_DATATYPE_ID], q_handle->query_string, table_key[TABLE_PERSON], table_key[TABLE_DATA]); + g_string_append_printf(query, " where (%s = %s) and", field_key[FIELD_PERSON_CONTACT_ID], field_key[FIELD_DATA_PERSON_ID]); + + if(strlen(condtion_sub_query) != 0) + { + if(use_sub_query == false) + g_string_append_printf(query, " %s = ? and", field_key[FIELD_PERSON_CONTACT_ID]); + else + g_string_append_printf(query, " %s in (%s) and", field_key[FIELD_PERSON_CONTACT_ID], condtion_sub_query); + } + g_string_append_printf(query, " (%s) order by %s", condition->str, field_key[FIELD_PERSON_CONTACT_ID]); + + } + break; + default: + break; + } + + g_string_free(condition, TRUE); + g_string_free(contact_condition, TRUE); +} + +query_error _query_result_set(advanced_handle_t* q_handle, int rc, int count, projection_type type, target_table_e join_table) +{ + query_error error_code = QUERY_SUCCESS; + + ADVANCED_SVC_TRACE("_query_result_set"); + + q_handle->result_set = g_new0(result_t, count + 1); + ADVANCED_CATCH_SET_ERROR((q_handle->result_set != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + q_handle->mapping_id_to_result_set = g_new0(mapping_list_t, count + 1); + while(rc == SQLITE_ROW) + { + error_code = _make_contact_info(q_handle, type, join_table); + if(error_code == QUERY_SET_LIMIT) + { + error_code = QUERY_SUCCESS; + break; + } + ADVANCED_CATCH_SET_ERROR((error_code == QUERY_SUCCESS), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + rc = _query_step(q_handle->hstmt); + } + + _query_finalize(q_handle->hstmt); + +CATCH: + return error_code; +} + +int _make_result_contact_list(advanced_handle_t* q_handle, int count, char* condtion_sub_query) +{ + ADVANCED_RETURN_VAL((q_handle->projection != NULL), {}, QUERY_NULL_PARAMETER, ("PROJECTION LIST IS NULL")); + + int rc = -1; + query_error error_code = QUERY_SUCCESS; + GString* query; + GString* projection; + char* loc = NULL; + projection_type type = NORMAL_CASE; + target_table_e value = ONLY_CONTACT; + + query = g_string_new(""); + projection = g_string_new(""); + + value = _check_join_case(q_handle); + ADVANCED_SVC_TRACE("value : %d", value); + + bool table_contact = false; + bool reorganize = false; + int data_field_count = 0; + + if(q_handle->query_string == NULL) + { + GList* tmp = q_handle->projection; + while(tmp) + { + projection_t* projection_info = (projection_t*)tmp->data; + + loc = strstr(projection_info->field, "contact."); + if(loc != NULL) + table_contact = true; + + loc = strstr(projection_info->field, "data.contact_id"); + if(loc != NULL) + reorganize = true; + + loc = strstr(projection_info->field, "data."); + if(loc != NULL) + data_field_count++; + + tmp = g_list_next(tmp); + } + + if(q_handle->query_type == QUERY_TO_PERSON) + g_string_append_printf(projection, "%s", field_key[FIELD_PERSON_CONTACT_ID]); + + if((table_contact == true && reorganize == true && data_field_count == 1) || (q_handle->assigned_datatype == 0)) + { + g_string_append_printf(projection, "%s", field_key[FIELD_CONTACT_CONTACT_ID]); + value = ONLY_CONTACT; + } + + if(projection->str[0] == '\0') + { + g_string_append_printf(projection, "%s", field_key[FIELD_DATA_CONTACT_ID]); + } + + GList* tmp_projection = q_handle->projection; + bool projection_duplicate = false; + while(tmp_projection) + { + projection_t* projection_info = (projection_t*)tmp_projection->data; + + if(strcmp(projection_info->field, field_key[FIELD_CONTACT_CONTACT_ID]) == 0) + projection_duplicate = true; + + if(strcmp(projection_info->field, field_key[FIELD_DATA_CONTACT_ID]) == 0) + projection_duplicate = true; + + loc = strstr(projection->str, projection_info->field); + if(loc == NULL && projection_duplicate == false) + { + g_string_append_printf(projection, ", %s", projection_info->field); + + projection_t* new_projection_info = NULL; + new_projection_info = g_new0(projection_t, 1); + ADVANCED_CATCH_SET_ERROR((new_projection_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + new_projection_info->field = g_strdup(projection_info->field); + q_handle->new_projection = g_list_append(q_handle->new_projection, new_projection_info); + } + + tmp_projection = g_list_next(tmp_projection); + projection_duplicate = false; + } + g_list_foreach(q_handle->projection, _free_projection_list, NULL); + g_list_free(q_handle->projection); + + q_handle->query_string = g_strdup(projection->str); + } + ADVANCED_SVC_TRACE("projection : %s", q_handle->query_string); + + if((strcmp(q_handle->query_string, field_key[FIELD_DATA_CONTACT_ID]) == 0) || (strcmp(q_handle->query_string, field_key[FIELD_CONTACT_CONTACT_ID]) == 0)) + type = ONLY_CONTACT_ID_FIELD; + + _construct_query(value, q_handle, query, condtion_sub_query, type); + + q_handle->hstmt = _query_prepare(query->str); + ADVANCED_CATCH_SET_ERROR((q_handle->hstmt != NULL), {}, QUERY_STATEMENT_FAIL, ("database prepare fail")); + + if(strlen(condtion_sub_query) != 0) + { + int i = 1; + if(q_handle->condition_category != NULL) + { + ADVANCED_SVC_TRACE("q_handle->condition_category : %s", q_handle->condition_category); + _query_bind_text(q_handle->hstmt, i, q_handle->condition_category); + }else + { + GList* tmp_condition_val = q_handle->condition_value; + while(tmp_condition_val) + { + condition_val_t* tmp_val = (condition_val_t*)tmp_condition_val->data; + if(tmp_val->indices_filter == false) + { + ADVANCED_SVC_TRACE("condition_val->value : %s", tmp_val->value); + + primitive_type type = _convert_check_attribute_primitive_type(tmp_val->attribute); + if(tmp_val->x_attribute == true) + type = STRING; + + if(type == INTEGER) + _query_bind_int(q_handle->hstmt, i++, tmp_val->int_value); + else if(type == STRING) + _query_bind_text(q_handle->hstmt, i++, tmp_val->value); + else if(type == REAL) + _query_bind_double(q_handle->hstmt, i++, tmp_val->real_value); + } + tmp_condition_val = g_list_next(tmp_condition_val); + } + } + } + + rc = _query_step(q_handle->hstmt); + ADVANCED_CATCH_SET_ERROR((rc == SQLITE_ROW), {}, QUERY_NO_RECORD, ("No record in database")); + + error_code = _query_result_set(q_handle, rc, count, type, value); + +CATCH: + g_string_free(query, TRUE); + g_string_free(projection, TRUE); + return error_code; +} + +bool _check_optimized_query(advanced_handle_t* q_handle, target_table_e join_table) +{ + bool is_optimized_query = false; + + if((q_handle->extra_info & CATEGORIES) == 0) + { + switch(join_table) + { + case ONLY_DATA: + case ONLY_DATA_FROM_PERSON_QUERY: + { + if(q_handle->all_datatype_in_query == DATATYPE_NAME) + is_optimized_query = true; + } + break; + case ONLY_PERSON: + is_optimized_query = true; + break; + default: + break; + } + } + ADVANCED_SVC_TRACE("is_optimized_query : %d ", is_optimized_query); + + return is_optimized_query; +} + +query_error _optimized_query_to_person_with_data(advanced_handle_t* q_handle, int count) +{ + query_error error_code = QUERY_SUCCESS; + int rc = -1; + + GString* query; + GString* projection; + GString* condition; + + projection = g_string_new(""); + query = g_string_new (""); + condition = g_string_new (""); + + if(q_handle->query_string == NULL) + { + g_string_append_printf(projection, "%s", field_key[FIELD_DATA_DATATYPE_ID]); + g_string_append_printf(projection, ", %s", field_key[FIELD_DATA_PERSON_ID]); + + GList* tmp_projection = q_handle->projection; + while(tmp_projection) + { + projection_t* projection_info = (projection_t*)tmp_projection->data; + + if(strcmp(projection_info->field, field_key[FIELD_PERSON_CONTACT_ID]) != 0) + { + g_string_append_printf(projection, ", %s", projection_info->field); + + projection_t* new_projection_info = NULL; + new_projection_info = g_new0(projection_t, 1); + ADVANCED_CATCH_SET_ERROR((new_projection_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + new_projection_info->field = g_strdup(projection_info->field); + q_handle->new_projection = g_list_append(q_handle->new_projection, new_projection_info); + } + tmp_projection = g_list_next(tmp_projection); + } + g_list_foreach(q_handle->projection, _free_projection_list, NULL); + g_list_free(q_handle->projection); + + q_handle->query_string = g_strdup(projection->str); + } + + g_string_append_printf(query, "select %s from %s ", q_handle->query_string, table_key[TABLE_DATA]); + + GList* tmp_datatype_list = q_handle->datatype_list; + while(tmp_datatype_list) + { + datatype_t* datatype_info = (datatype_t*)tmp_datatype_list->data; + g_string_append_printf(condition, "where (%s and %s = %d)", q_handle->use_normal_field_key->str, datatype_info->field, datatype_info->datatype); + tmp_datatype_list = g_list_next(tmp_datatype_list); + } + + if(q_handle->order->str[0] != '\0') + g_string_append_printf(query, " %s order by %s", condition->str, q_handle->order->str); + else + { + g_string_append_printf(query, " %s order by %s", condition->str, field_key[FIELD_DATA_PERSON_ID]); + } + + q_handle->hstmt = _query_prepare(query->str); + ADVANCED_CATCH_SET_ERROR((q_handle->hstmt != NULL), {}, QUERY_STATEMENT_FAIL, ("database prepare fail")); + + if(q_handle->use_normal_field_key->str[0] != '\0') + { + GList* tmp_condition_val = q_handle->condition_value; + while(tmp_condition_val) + { + condition_val_t* tmp_val = (condition_val_t*)tmp_condition_val->data; + ADVANCED_SVC_TRACE("condition_val->value : %s", tmp_val->value); + + _query_bind_text(q_handle->hstmt, 1, tmp_val->value); + tmp_condition_val = g_list_next(tmp_condition_val); + } + } + + rc = _query_step(q_handle->hstmt); + ADVANCED_CATCH_SET_ERROR((rc == SQLITE_ROW), {}, QUERY_NO_RECORD, ("No record in database")); + + error_code = _query_result_set(q_handle, rc, count, NORMAL_CASE, JOIN_PERSON_DATA); + +CATCH: + g_string_free(query, TRUE); + g_string_free(projection, TRUE); + g_string_free(condition, TRUE); + + if(error_code != QUERY_SUCCESS) + { + _query_finalize(q_handle->hstmt); + } + + return error_code; +} + +query_error _optimized_query_join_person_data(advanced_handle_t* q_handle, int count) +{ + int rc = -1; + query_error error_code = QUERY_SUCCESS; + GString* query; + GString* projection; + GString* condition; + + char* loc = NULL; + query = g_string_new(""); + projection = g_string_new(""); + condition = g_string_new(""); + + if(q_handle->query_string == NULL) + { + g_string_append_printf(projection, "%s", field_key[FIELD_PERSON_CONTACT_ID]); + + GList* tmp_projection = q_handle->projection; + bool projection_duplicate = false; + while(tmp_projection) + { + projection_t* projection_info = (projection_t*)tmp_projection->data; + + loc = strstr(projection->str, projection_info->field); + if(loc == NULL) + { + g_string_append_printf(projection, ", %s", projection_info->field); + + projection_t* new_projection_info = NULL; + new_projection_info = g_new0(projection_t, 1); + ADVANCED_CATCH_SET_ERROR((new_projection_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + new_projection_info->field = g_strdup(projection_info->field); + q_handle->new_projection = g_list_append(q_handle->new_projection, new_projection_info); + } + + tmp_projection = g_list_next(tmp_projection); + projection_duplicate = false; + } + g_list_foreach(q_handle->projection, _free_projection_list, NULL); + g_list_free(q_handle->projection); + + q_handle->query_string = g_strdup(projection->str); + } + + ADVANCED_SVC_TRACE("projection : %s", q_handle->query_string); + + g_string_append_printf(query, "select %s, %s", field_key[FIELD_DATA_DATATYPE_ID], q_handle->query_string); + g_string_append_printf(query, " from %s", q_handle->table_list->str); + + GList* tmp_datatype_list = q_handle->datatype_list; + while(tmp_datatype_list) + { + datatype_t* datatype_info = (datatype_t*)tmp_datatype_list->data; + g_string_append_printf(condition, "where (%s and %s = %d) and ", q_handle->use_normal_field_key->str, datatype_info->field, datatype_info->datatype); + tmp_datatype_list = g_list_next(tmp_datatype_list); + } + + g_string_append_printf(condition, " (%s = %s)", field_key[FIELD_PERSON_CONTACT_ID], field_key[FIELD_DATA_PERSON_ID]); + + if(q_handle->order->str[0] != '\0') + g_string_append_printf(query, " %s order by %s", condition->str, q_handle->order->str); + else + g_string_append_printf(query, " %s order by %s", condition->str, field_key[FIELD_PERSON_CONTACT_ID]); + + q_handle->hstmt = _query_prepare(query->str); + ADVANCED_CATCH_SET_ERROR((q_handle->hstmt != NULL), {}, QUERY_STATEMENT_FAIL, ("database prepare fail")); + + if(strlen(q_handle->use_normal_field_key->str) != 0) + { + GList* tmp_condition_val = q_handle->condition_value; + while(tmp_condition_val) + { + condition_val_t* tmp_val = (condition_val_t*)tmp_condition_val->data; + ADVANCED_SVC_TRACE("condition_val->value : %s", tmp_val->value); + + _query_bind_text(q_handle->hstmt, 1, tmp_val->value); + tmp_condition_val = g_list_next(tmp_condition_val); + } + } + + rc = _query_step(q_handle->hstmt); + ADVANCED_CATCH_SET_ERROR((rc == SQLITE_ROW), {}, QUERY_NO_RECORD, ("No record in database")); + + error_code = _query_result_set(q_handle, rc, count, NORMAL_CASE, JOIN_PERSON_DATA); + +CATCH: + g_string_free(query, TRUE); + g_string_free(projection, TRUE); + g_string_free(condition, TRUE); + + if(error_code != QUERY_SUCCESS) + { + _query_finalize(q_handle->hstmt); + } + + return error_code; +} + +query_error _get_categories_list(advanced_handle_t* q_handle, int count, char* condition_query) +{ + GString* query; + stmt hstmt; + int rc = -1; + int pos = 0; + query_error error_code = QUERY_SUCCESS; + + query = g_string_new (""); + + g_string_append_printf(query, "select a.%s, a.%s, b.%s from %s a, %s b where (a.%s = b.%s)", + relation_field_key[FIELD_GROUP_RELATION_CONTACT_ID], relation_field_key[FIELD_GROUP_RELATION_GROUP_ID], group_field_key[FIELD_GROUP_NAME], + table_key[TABLE_GROUP_RELATION], table_key[TABLE_GROUP], + group_field_key[FIELD_GROUP_ID], relation_field_key[FIELD_GROUP_RELATION_GROUP_ID]); + + if(strlen(condition_query) != 0) + g_string_append_printf(query, " and a.%s in (%s)", relation_field_key[FIELD_GROUP_RELATION_CONTACT_ID], condition_query); + + g_string_append_printf(query, " order by a.%s", relation_field_key[FIELD_GROUP_RELATION_CONTACT_ID]); + + hstmt = _query_prepare(query->str); + ADVANCED_CATCH_SET_ERROR((hstmt != NULL), {}, QUERY_STATEMENT_FAIL, ("Database prepare fail")); + + if(q_handle->condition_category != NULL) + { + _query_bind_text(hstmt, 1, q_handle->condition_category); + }else if(strlen(condition_query) != 0) + { + GList* tmp_condition_val = q_handle->condition_value; + int i = 1; + while(tmp_condition_val) + { + condition_val_t* tmp_val = (condition_val_t*)tmp_condition_val->data; + + if(tmp_val->indices_filter == false) + { + primitive_type type = _convert_check_attribute_primitive_type(tmp_val->attribute); + if(tmp_val->x_attribute == true) + type = STRING; + + if(type == INTEGER) + _query_bind_int(hstmt, i++, tmp_val->int_value); + else if(type == STRING) + _query_bind_text(hstmt, i++, tmp_val->value); + else if(type == REAL) + _query_bind_double(hstmt, i++, tmp_val->real_value); + } + tmp_condition_val = g_list_next(tmp_condition_val); + } + } + rc = _query_step(hstmt); + ADVANCED_CATCH_SET_ERROR((rc == SQLITE_ROW), {}, QUERY_NO_RECORD, ("No record in database")); + + while(rc == SQLITE_ROW) + { + if(pos > count) + break; + + q_handle->category[pos].contact_id = _query_column_int(hstmt, 0); + q_handle->category[pos].group_id = _query_column_int(hstmt, 1); + q_handle->category[pos].name = g_strdup(_query_column_text(hstmt, 2)); + + ADVANCED_SVC_TRACE("q_handle->category[%d].contact_id : %d", pos, q_handle->category[pos].contact_id); + + if(q_handle->category[pos].contact_id == q_handle->category[pos - 1].contact_id) + q_handle->category[pos].sibling = true; + + pos++; + + rc = _query_step(hstmt); + } + q_handle->category_total_count = pos; + _query_finalize(hstmt); + +CATCH: + g_string_free(query, TRUE); + return error_code; +} + +query_error _construct_optimize_query(advanced_handle_t* q_handle, GString* query, target_table_e join_table, projection_type type, char* sub_query) +{ + GString* condition; + bool is_first = true; + query_error error_code = QUERY_SUCCESS; + condition = g_string_new (""); + bool is_sub_query = false; + + if(sub_query[0] != '\0') + is_sub_query = true; + + if(is_sub_query) + { + switch(join_table) + { + case ONLY_DATA: + g_string_append_printf(condition, " %s in (%s) and ", field_key[FIELD_DATA_CONTACT_ID], sub_query); + break; + case ONLY_PERSON: + case ONLY_DATA_FROM_PERSON_QUERY: + g_string_append_printf(condition, " %s in (%s) and ", field_key[FIELD_PERSON_CONTACT_ID], sub_query); + break; + default: + break; + } + } + + if(join_table == ONLY_DATA || join_table == ONLY_DATA_FROM_PERSON_QUERY) + { + GList* tmp_datatype_list = q_handle->datatype_list; + is_first = true; + while(tmp_datatype_list) + { + datatype_t* datatype_info = (datatype_t*)tmp_datatype_list->data; + + if(is_first) + { + if(q_handle->use_normal_field_key->str[0] != '\0' && is_sub_query == false) + { + g_string_append_printf(condition, "%s and %s = %d", q_handle->use_normal_field_key->str, datatype_info->field, datatype_info->datatype); + }else + g_string_append_printf(condition, "%s = %d", datatype_info->field, datatype_info->datatype); + }else + { + g_string_append_printf(condition, " or %s = %d", datatype_info->field, datatype_info->datatype); + } + + tmp_datatype_list = g_list_next(tmp_datatype_list); + is_first = false; + } + } + + switch(join_table) + { + case ONLY_DATA: + { + if(type == ONLY_CONTACT_ID_FIELD) + g_string_append_printf(query, "select %s from %s", q_handle->query_string, table_key[TABLE_DATA]); + else + g_string_append_printf(query, "select %s, %s from %s", field_key[FIELD_DATA_DATATYPE_ID], q_handle->query_string, table_key[TABLE_DATA]); + + if(condition->str[0] != '\0') + g_string_append_printf(query, " where (%s)", condition->str); + + if(q_handle->order->str[0] != '\0') + g_string_append_printf(query, " order by %s", q_handle->order->str); + else + g_string_append_printf(query, " order by %s", field_key[FIELD_DATA_CONTACT_ID]); + } + break; + case ONLY_DATA_FROM_PERSON_QUERY: + { + if(type == ONLY_CONTACT_ID_FIELD) + g_string_append_printf(query, "select %s from %s", q_handle->query_string, table_key[TABLE_DATA]); + else + g_string_append_printf(query, "select %s, %s from %s", field_key[FIELD_DATA_DATATYPE_ID], q_handle->query_string, table_key[TABLE_DATA]); + + if(condition->str[0] != '\0') + g_string_append_printf(query, " where (%s)", condition->str); + + if(q_handle->order->str[0] != '\0') + g_string_append_printf(query, " order by %s", q_handle->order->str); + else + g_string_append_printf(query, " order by %s", field_key[FIELD_PERSON_CONTACT_ID]); + } + break; + case ONLY_PERSON: + { + g_string_append_printf(query, "select %s from %s", q_handle->query_string, table_key[TABLE_PERSON]); + + if(q_handle->use_normal_field_key->str[0] != '\0') + g_string_append_printf(query, " where (%s)", q_handle->use_normal_field_key->str); + + if(q_handle->order->str[0] != '\0') + g_string_append_printf(query, " order by %s", q_handle->order->str); + else + g_string_append_printf(query, " order by %s", field_key[FIELD_PERSON_CONTACT_ID]); + } + break; + default: + break; + } + + g_string_free(condition, TRUE); + return error_code; +} + +API query_error query_get_result_contact(ADVANCED_HANDLE handle) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + + int rc = -1; + query_error error_code = QUERY_SUCCESS; + GString* query; + GString* projection; + char* loc = NULL; + int count = 0; + projection_type type = NORMAL_CASE; + int i = 1; + bool is_optimized_query = false; + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + + if(q_handle->result_set) + { + ADVANCED_SVC_TRACE("------------------------------ GET NEXT CONTACT INFO ------------------------------ "); + + if(q_handle->order->str[0] != '\0') + { + if(q_handle->is_optimized_query) + { + q_handle->return_array_pos++; + ADVANCED_CATCH_SET_ERROR((q_handle->return_array_pos < q_handle->total_result_set_count), {}, QUERY_NO_RECORD, ("no record")); + ADVANCED_CATCH_SET_ERROR((q_handle->result_set[q_handle->return_array_pos].is_occupied == true), {}, QUERY_NO_RECORD, ("no record")); + }else + { + q_handle->pos++; + ADVANCED_CATCH_SET_ERROR((q_handle->pos < q_handle->total_result_set_count), {}, QUERY_NO_RECORD, ("no record")); + q_handle->return_array_pos = q_handle->ordering_list[q_handle->pos].ordered_pos; + } + }else + { + q_handle->return_array_pos++; + ADVANCED_CATCH_SET_ERROR((q_handle->return_array_pos < q_handle->total_result_set_count), {}, QUERY_NO_RECORD, ("no record")); + ADVANCED_CATCH_SET_ERROR((q_handle->result_set[q_handle->return_array_pos].is_occupied == true), {}, QUERY_NO_RECORD, ("no record")); + } + }else + { + ADVANCED_SVC_TRACE("------------------------------ GENERATE RESULT SET ------------------------------ "); + + if(q_handle->query_type == QUERY_TO_PERSON) + _query_get_count(table_key[TABLE_PERSON], q_handle->query_type, &count); + else if(q_handle->query_type == QUERY_TO_CONTACT) + _query_get_count(table_key[TABLE_CONTACT], q_handle->query_type, &count); + ADVANCED_RETURN_VAL((count != 0), {}, QUERY_NO_RECORD, ("NO RECORD")); + + query = g_string_new (""); + + target_table_e join_table = _check_join_case(q_handle); + q_handle->join_table = join_table; + + is_optimized_query = _check_optimized_query(q_handle, join_table); + + if(is_optimized_query == true) + { + ADVANCED_SVC_TRACE("!!!!!! EXECUTE OPTIMIZED QUERY !!!!!!"); + q_handle->is_optimized_query = true; + projection = g_string_new(""); + + if(q_handle->query_string == NULL) + { + if(join_table == ONLY_DATA || join_table == ONLY_DATA_FROM_PERSON_QUERY) + g_string_append_printf(projection, "%s", field_key[FIELD_DATA_CONTACT_ID]); + else + g_string_append_printf(projection, "%s", field_key[FIELD_PERSON_CONTACT_ID]); + + GList* tmp_projection = q_handle->projection; + while(tmp_projection) + { + projection_t* projection_info = (projection_t*)tmp_projection->data; + + loc = strstr(projection->str, projection_info->field); + if(loc == NULL) + { + g_string_append_printf(projection, ", %s", projection_info->field); + + projection_t* new_projection_info = NULL; + new_projection_info = g_new0(projection_t, 1); + ADVANCED_CATCH_SET_ERROR((new_projection_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + new_projection_info->field = g_strdup(projection_info->field); + q_handle->new_projection = g_list_append(q_handle->new_projection, new_projection_info); + } + tmp_projection = g_list_next(tmp_projection); + } + g_list_foreach(q_handle->projection, _free_projection_list, NULL); + g_list_free(q_handle->projection); + + q_handle->query_string = g_strdup(projection->str); + } + + if((strcmp(q_handle->query_string, field_key[FIELD_DATA_CONTACT_ID]) == 0) || (strcmp(q_handle->query_string, field_key[FIELD_PERSON_CONTACT_ID]) == 0)) + type = ONLY_CONTACT_ID_FIELD; + + GString* sub_query; + sub_query = g_string_new(""); + + if(q_handle->condition_datatype != DATATYPE_NAME && q_handle->condition_datatype != DATATYPE_INVALID) + _make_contact_id_list_by_condition_part(q_handle, count, sub_query); + + error_code = _construct_optimize_query(q_handle, query, join_table, type, sub_query->str); + ADVANCED_CATCH_SET_ERROR((error_code == QUERY_SUCCESS), {}, error_code, ("CONSTRUCT QUERY FAIL")); + + q_handle->hstmt = _query_prepare(query->str); + ADVANCED_CATCH_SET_ERROR((q_handle->hstmt != NULL), {}, QUERY_STATEMENT_FAIL, ("database prepare fail")); + + if(q_handle->use_normal_field_key->str[0] != '\0') + { + GList* tmp_condition_val = q_handle->condition_value; + while(tmp_condition_val) + { + condition_val_t* tmp_val = (condition_val_t*)tmp_condition_val->data; + if(tmp_val->indices_filter == false) + { + ADVANCED_SVC_TRACE("condition_val->value : %s", tmp_val->value); + primitive_type type = _convert_check_attribute_primitive_type(tmp_val->attribute); + if(tmp_val->x_attribute == true) + type = STRING; + + if(type == INTEGER) + _query_bind_int(q_handle->hstmt, i++, tmp_val->int_value); + else if(type == STRING) + _query_bind_text(q_handle->hstmt, i++, tmp_val->value); + else if(type == REAL) + _query_bind_double(q_handle->hstmt, i++, tmp_val->real_value); + } + + tmp_condition_val = g_list_next(tmp_condition_val); + } + } + + rc = _query_step(q_handle->hstmt); + ADVANCED_CATCH_SET_ERROR((rc == SQLITE_ROW), {}, QUERY_NO_RECORD, ("No record in database")); + + error_code = _query_result_set(q_handle, rc, count, type, join_table); + + g_string_free(projection, TRUE); + g_string_free(query, TRUE); + g_string_free (sub_query, TRUE); + + }else + { + ADVANCED_SVC_TRACE("!!!!!! EXECUTE NORMAL QUERY !!!!!!"); + +// generate contact id list + GString* sub_query; + sub_query = g_string_new(""); + + if(q_handle->condition_category != NULL) + { + g_string_append_printf(sub_query, "select distinct(a.%s) from %s a, %s b where (a.%s = b.%s) and b.%s %s ?", + relation_field_key[FIELD_GROUP_RELATION_CONTACT_ID], table_key[TABLE_GROUP_RELATION], + table_key[TABLE_GROUP], group_field_key[FIELD_GROUP_ID], relation_field_key[FIELD_GROUP_RELATION_GROUP_ID], + group_field_key[FIELD_GROUP_NAME], q_handle->condition_category_op); + }else + error_code = _make_contact_id_list_by_condition_part(q_handle, count, sub_query); + +// generate result set + error_code = _make_result_contact_list(q_handle, count, sub_query->str); +// ordering + _make_order_list(q_handle, count, join_table); + +// get categories + int category_count = 0; + if((q_handle->extra_info & CATEGORIES) != 0) + { + _query_get_count(table_key[TABLE_GROUP_RELATION], q_handle->query_type, &category_count); + q_handle->category = g_new0(categories_info, category_count + 1); + if(category_count != 0) + _get_categories_list(q_handle, category_count, sub_query->str); + } + + g_string_free (sub_query, TRUE); + } + ADVANCED_CATCH_SET_ERROR((q_handle->total_result_set_count != 0), {}, QUERY_NO_RECORD, ("NO RESULT CONTACT LIST")); + } + +CATCH: + if(error_code != QUERY_SUCCESS) + { + } + + return error_code; +} + +API query_error query_finalize(ADVANCED_HANDLE handle) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + + query_error error_code = QUERY_SUCCESS; + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + + _free_handle_info(q_handle); + q_handle = NULL; + + error_code = _db_finish(); + + return error_code; +} + +query_error _set_exists_condition(ADVANCED_HANDLE handle, contact_attribute_e attribute) +{ + query_error error_code = QUERY_SUCCESS; + predefine_datatype datatype = DATATYPE_INVALID; + db_datatype db_datatype_id = DB_DATATYPE_INVALID; + //char* condition = NULL; + char* table = NULL; + condition_table_t* table_info = NULL; + alias_key_e tmp_current_alias = ALIAS_INVALID; + char* column_name = NULL; + char* normal_column_name = NULL; + + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + ADVANCED_RETURN_VAL((q_handle->condition_category == NULL), {}, QUERY_GROUP_CASE, ("GROUP QUERY CASE")); + + error_code = _check_extra_contact_info(q_handle, EXTRA_INFO_TYPE_CONDITION, attribute); + ADVANCED_RETURN_VAL((error_code != QUERY_SUCCESS), {}, QUERY_FAIL, ("NOT SUPPORT")); + error_code = QUERY_SUCCESS; + + column_name = _convert_attribute_to_condition_column_name(attribute); + normal_column_name = _convert_attribute_to_column_name(attribute); + + datatype = _convert_attribute_to_mimetype_id(attribute); + db_datatype_id = _convert_datatype_to_db_type(datatype); + + table = _convert_attribute_to_table_name(attribute); + tables_e table_type = _contact_table_name_to_table_type(table); + q_handle->query_table = q_handle->query_table | table_type; + + if(q_handle->current_alias != ALIAS_INVALID) + { + if((q_handle->condition_datatype & datatype) == 0 ) + { + q_handle->current_alias++; + tmp_current_alias = q_handle->current_alias; + + table_info = g_new0(condition_table_t, 1); + table_info->alias = q_handle->current_alias; + table_info->table = g_strdup(table); + q_handle->condition_table_list = g_list_append(q_handle->condition_table_list, table_info); + }else + { + GList* tmp_condition_list = q_handle->condition_list; + while(tmp_condition_list) + { + condition_list_t* tmp_info = (condition_list_t*)tmp_condition_list->data; + + if(tmp_info->datatype == db_datatype_id) + { + tmp_current_alias = tmp_info->current_alias; + break; + } + tmp_condition_list = g_list_next(tmp_condition_list); + } + } + }else + { + q_handle->current_alias++; + tmp_current_alias = q_handle->current_alias; + + table_info = g_new0(condition_table_t, 1); + table_info->alias = q_handle->current_alias; + table_info->table = g_strdup(table); + q_handle->condition_table_list = g_list_append(q_handle->condition_table_list, table_info); + } + + if(db_datatype_id != DB_DATATYPE_INVALID) + { + g_string_append_printf(q_handle->use_normal_field_key, "(%s = %d)", condition_field_key[FIELD_DATA_DATATYPE_ID], db_datatype_id); + g_string_append_printf(q_handle->condition_text, "(%s.%s = %d)", alias_key[tmp_current_alias], condition_field_key[FIELD_DATA_DATATYPE_ID], db_datatype_id); + + condition_list_t* condition_info = NULL; + condition_info = g_new0(condition_list_t, 1); + condition_info->current_alias = tmp_current_alias; + condition_info->datatype = db_datatype_id; + q_handle->condition_list = g_list_append(q_handle->condition_list, condition_info); + }else + { + q_handle->optimize_condition = false; + g_string_append_printf(q_handle->use_contact_table_id, "(%s is not null)", field_key[FIELD_CONTACT_CONTACT_ID]); + g_string_append_printf(q_handle->use_normal_field_key, "(%s is not null)", normal_column_name); + g_string_append_printf(q_handle->condition_text, "(%s.%s is not null)", alias_key[tmp_current_alias], column_name); + } + + q_handle->condition_datatype = q_handle->condition_datatype | datatype; + + return error_code; +} + +API query_error query_set_condition(ADVANCED_HANDLE handle, contact_attribute_e attribute, condition_e attr, const char* value) +{ + query_error error_code = QUERY_SUCCESS; + predefine_datatype datatype = DATATYPE_INVALID; + db_datatype db_datatype_id = DB_DATATYPE_INVALID; + char* column_name = NULL; + char* normal_column_name = NULL; + char* condition = NULL; + char* table = NULL; + bool is_person_attr = false; + condition_table_t* table_info = NULL; + alias_key_e tmp_current_alias = ALIAS_INVALID; + + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + ADVANCED_RETURN_VAL((attribute < ATTRIBUTE_MAX), {}, QUERY_INVALID_ATTRIBUTE, ("INVALID CONTACT ATTRIBUTE")); + ADVANCED_RETURN_VAL((attr < CONDITION_MAX), {}, QUERY_INVALID_TYPE, ("INVALID CONTACT CONDITION")); + + if(attr == EXISTS) + { + error_code = _set_exists_condition(handle, attribute); + return error_code; + } + ADVANCED_RETURN_VAL((value != NULL), {}, QUERY_NULL_PARAMETER, ("INVALID VALUE")); + + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + ADVANCED_RETURN_VAL((q_handle->condition_category == NULL), {}, QUERY_GROUP_CASE, ("GROUP QUERY CASE")); + + ADVANCED_SVC_TRACE("condition value : %s", value); + condition = _convert_condition_to_string(attr); + + error_code = _check_extra_contact_info(q_handle, EXTRA_INFO_TYPE_CONDITION, attribute); + if(error_code == QUERY_SUCCESS) + { + ADVANCED_RETURN_VAL((q_handle->condition_text->str[0] == '\0'), {}, QUERY_GROUP_CASE, ("CAN NOT ASSIGN GROUP CONDITION")); + q_handle->condition_category = g_strdup(value); + q_handle->condition_category_op = g_strdup(condition); + return error_code; + } + error_code = QUERY_SUCCESS; + + if(q_handle->query_type == QUERY_TO_PERSON) + { + column_name = _convert_person_attribute_to_condition_column_name(attribute); + normal_column_name = _convert_person_attribute_to_column_name(attribute); + } + + if(column_name == NULL) + { +// column_name = _convert_attribute_to_condition_normalize_column(attribute); +// normal_column_name = _convert_attribute_to_normalize_column(attribute); + +// if(column_name == NULL) + { + column_name = _convert_attribute_to_condition_column_name(attribute); + normal_column_name = _convert_attribute_to_column_name(attribute); + } + } + + if(q_handle->query_type == QUERY_TO_PERSON) + is_person_attr = _convert_person_attribute_to_mimetype_id(attribute); + + if(is_person_attr == false) + { + datatype = _convert_attribute_to_mimetype_id(attribute); + db_datatype_id = _convert_datatype_to_db_type(datatype); + } + + if(q_handle->query_type == QUERY_TO_PERSON) + table = _convert_person_attribute_to_table_name(attribute); + + if(table == NULL) + table = _convert_attribute_to_table_name(attribute); + tables_e table_type = _contact_table_name_to_table_type(table); + q_handle->query_table = q_handle->query_table | table_type; + + if(q_handle->current_alias != ALIAS_INVALID) + { + if((q_handle->condition_datatype & datatype) == 0 ) + { + q_handle->current_alias++; + tmp_current_alias = q_handle->current_alias; + + table_info = g_new0(condition_table_t, 1); + table_info->alias = q_handle->current_alias; + table_info->table = g_strdup(table); + q_handle->condition_table_list = g_list_append(q_handle->condition_table_list, table_info); + }else + { + GList* tmp_condition_list = q_handle->condition_list; + while(tmp_condition_list) + { + condition_list_t* tmp_info = (condition_list_t*)tmp_condition_list->data; + + if(tmp_info->datatype == db_datatype_id) + { + tmp_current_alias = tmp_info->current_alias; + break; + } + tmp_condition_list = g_list_next(tmp_condition_list); + } + } + }else + { + q_handle->current_alias++; + tmp_current_alias = q_handle->current_alias; + + table_info = g_new0(condition_table_t, 1); + table_info->alias = q_handle->current_alias; + table_info->table = g_strdup(table); + q_handle->condition_table_list = g_list_append(q_handle->condition_table_list, table_info); + } + + if(db_datatype_id != DB_DATATYPE_INVALID) + { + g_string_append_printf(q_handle->use_normal_field_key, "(%s %s ? and %s = %d)", + normal_column_name, condition, condition_field_key[FIELD_DATA_DATATYPE_ID], db_datatype_id); + + g_string_append_printf(q_handle->condition_text, "(%s.%s %s ? and %s.%s = %d)", + alias_key[tmp_current_alias], column_name, condition, alias_key[tmp_current_alias], condition_field_key[FIELD_DATA_DATATYPE_ID], db_datatype_id); + + condition_list_t* condition_info = NULL; + condition_info = g_new0(condition_list_t, 1); + condition_info->column_name = g_strdup(column_name); + condition_info->current_alias = tmp_current_alias; + condition_info->condition = g_strdup(condition); + condition_info->datatype = db_datatype_id; + + q_handle->condition_list = g_list_append(q_handle->condition_list, condition_info); + + }else + { + q_handle->optimize_condition = false; + g_string_append_printf(q_handle->use_contact_table_id, "(%s %s ?)", field_key[FIELD_CONTACT_CONTACT_ID], condition); + + g_string_append_printf(q_handle->use_normal_field_key, "(%s %s ?)", normal_column_name, condition); + + g_string_append_printf(q_handle->condition_text, "(%s.%s %s ?)", alias_key[tmp_current_alias], column_name, condition); + } + + primitive_type type = _convert_check_attribute_primitive_type(attribute); + condition_val_t* condition_txt = NULL; + condition_txt = g_new0(condition_val_t, 1); + + condition_txt->attribute = attribute; + if(type == INTEGER) + { + if(attribute == ACCOUNT_ID) + { + int total_count = 0; + int integer_value = atoi(value); + + get_all_addressbook_id(&total_count); + GList* tmp_list = g_addressbook_list; + while(tmp_list) + { + addressbook_list* info = (addressbook_list*)tmp_list->data; + if(integer_value == info->account_id) + { + condition_txt->int_value = info->addressbook_id; + break; + } + tmp_list = g_list_next(tmp_list); + } + }else + condition_txt->int_value = _convert_type_string_to_int(attribute, value); + }else if(type == STRING) + { + condition_txt->value = g_strdup(value); + }else if(type == REAL) + condition_txt->real_value = atof(value); + + q_handle->condition_value = g_list_append(q_handle->condition_value, condition_txt); + + q_handle->condition_datatype = q_handle->condition_datatype | datatype; + + return error_code; +} + +API query_error fetch_next_row(ADVANCED_HANDLE handle) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + query_error error_code = QUERY_SUCCESS; + + ADVANCED_RETURN_VAL((q_handle->result_set[q_handle->return_array_pos].contact_info != NULL), {}, QUERY_NO_RECORD, ("CONTACT INFO IS NULL")); + + switch(q_handle->current_datatype) + { + case DATATYPE_INVALID: + if(q_handle->query_type == QUERY_TO_CONTACT) + q_handle->result_set[q_handle->return_array_pos].contact_info->get_raw_contact_info = true; + else + q_handle->result_set[q_handle->return_array_pos].contact_info->get_person_info = true; + ADVANCED_CATCH_SET_ERROR(false, {}, QUERY_NO_NEXT_ROW, ("NOT MULTIPLE VALUE")); + break; + case DATATYPE_NUMBER: + { + GList* tmp_list = q_handle->result_set[q_handle->return_array_pos].contact_info->number_list; + if(tmp_list) + { + number_t* num_info = (number_t*)tmp_list->data; + + _free_num_info(q_handle->result_set[q_handle->return_array_pos].contact_info->num_info); + + q_handle->result_set[q_handle->return_array_pos].contact_info->num_info = g_new0(number_t, 1); + ADVANCED_CATCH_SET_ERROR((q_handle->result_set[q_handle->return_array_pos].contact_info->num_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + q_handle->result_set[q_handle->return_array_pos].contact_info->num_info->number = g_strdup(num_info->number); + q_handle->result_set[q_handle->return_array_pos].contact_info->num_info->number_type = g_strdup(num_info->number_type); + + ADVANCED_SVC_TRACE("number : %s", q_handle->result_set[q_handle->return_array_pos].contact_info->num_info->number); + _free_num_info((number_t*)tmp_list->data); + q_handle->result_set[q_handle->return_array_pos].contact_info->number_list = g_list_next(tmp_list); + } + else + { + ADVANCED_CATCH_SET_ERROR(false, {}, QUERY_NO_RECORD, ("no record")); + } + } + break; + case DATATYPE_EMAIL: + { + GList* tmp_list = q_handle->result_set[q_handle->return_array_pos].contact_info->email_list; + if(tmp_list) + { + email_t* email_info = (email_t*)tmp_list->data; + + _free_email_info(q_handle->result_set[q_handle->return_array_pos].contact_info->email_info); + + q_handle->result_set[q_handle->return_array_pos].contact_info->email_info = g_new0(email_t, 1); + ADVANCED_CATCH_SET_ERROR((q_handle->result_set[q_handle->return_array_pos].contact_info->email_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + q_handle->result_set[q_handle->return_array_pos].contact_info->email_info->email_addr = g_strdup(email_info->email_addr); + q_handle->result_set[q_handle->return_array_pos].contact_info->email_info->email_type = g_strdup(email_info->email_type); + + ADVANCED_SVC_TRACE("email_addr : %s", q_handle->result_set[q_handle->return_array_pos].contact_info->email_info->email_addr); + _free_email_info((email_t*)tmp_list->data); + q_handle->result_set[q_handle->return_array_pos].contact_info->email_list = g_list_next(tmp_list); + } + else + { + ADVANCED_CATCH_SET_ERROR(false, {}, QUERY_NO_RECORD, ("no record")); + } + } + break; + case DATATYPE_URL: + { + GList* tmp_list = q_handle->result_set[q_handle->return_array_pos].contact_info->url_list; + if(tmp_list) + { + url_t* url_info = (url_t*)tmp_list->data; + + _free_url_info(q_handle->result_set[q_handle->return_array_pos].contact_info->url_info); + + q_handle->result_set[q_handle->return_array_pos].contact_info->url_info = g_new0(url_t, 1); + ADVANCED_CATCH_SET_ERROR((q_handle->result_set[q_handle->return_array_pos].contact_info->url_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + q_handle->result_set[q_handle->return_array_pos].contact_info->url_info->url_addr = g_strdup(url_info->url_addr); + q_handle->result_set[q_handle->return_array_pos].contact_info->url_info->url_type = g_strdup(url_info->url_type); + + ADVANCED_SVC_TRACE("url_addr : %s", q_handle->result_set[q_handle->return_array_pos].contact_info->url_info->url_addr); + _free_url_info((url_t*)tmp_list->data); + q_handle->result_set[q_handle->return_array_pos].contact_info->url_list = g_list_next(tmp_list); + } + else + { + ADVANCED_CATCH_SET_ERROR(false, {}, QUERY_NO_RECORD, ("no record")); + } + } + break; + case DATATYPE_NICK_NAME : + { + GList* tmp_list = q_handle->result_set[q_handle->return_array_pos].contact_info->nickname_list; + if(tmp_list) + { + nick_name_t* nick_info = (nick_name_t*)tmp_list->data; + + _free_nick_info(q_handle->result_set[q_handle->return_array_pos].contact_info->nick_info); + + q_handle->result_set[q_handle->return_array_pos].contact_info->nick_info = g_new0(nick_name_t, 1); + ADVANCED_CATCH_SET_ERROR((q_handle->result_set[q_handle->return_array_pos].contact_info->nick_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + q_handle->result_set[q_handle->return_array_pos].contact_info->nick_info->nick_name = g_strdup(nick_info->nick_name); + + ADVANCED_SVC_TRACE("nick_name : %s", q_handle->result_set[q_handle->return_array_pos].contact_info->nick_info->nick_name); + _free_nick_info((nick_name_t*)tmp_list->data); + q_handle->result_set[q_handle->return_array_pos].contact_info->nickname_list = g_list_next(tmp_list); + } + else + { + ADVANCED_CATCH_SET_ERROR(false, {}, QUERY_NO_RECORD, ("no record")); + } + } + break; + case DATATYPE_ADDRESS : + { + GList* tmp_list = q_handle->result_set[q_handle->return_array_pos].contact_info->address_list; + if(tmp_list) + { + address_t* address_info = (address_t*)tmp_list->data; + + _free_address_info(q_handle->result_set[q_handle->return_array_pos].contact_info->address_info); + + q_handle->result_set[q_handle->return_array_pos].contact_info->address_info = g_new0(address_t, 1); + ADVANCED_CATCH_SET_ERROR((q_handle->result_set[q_handle->return_array_pos].contact_info->address_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->country = g_strdup(address_info->country); + q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->region = g_strdup(address_info->region); + q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->county= g_strdup(address_info->county); + q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->city = g_strdup(address_info->city); + q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->street = g_strdup(address_info->street); + q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->postal_code = g_strdup(address_info->postal_code); + q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->addtional = g_strdup(address_info->addtional); + + ADVANCED_SVC_TRACE("street : %s", q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->street); + _free_address_info((address_t*)tmp_list->data); + q_handle->result_set[q_handle->return_array_pos].contact_info->address_list = g_list_next(tmp_list); + } + else + { + ADVANCED_CATCH_SET_ERROR(false, {}, QUERY_NO_RECORD, ("no record")); + } + } + break; + case DATATYPE_ORGANIZATION : + { + GList* tmp_list = q_handle->result_set[q_handle->return_array_pos].contact_info->organization_list; + if(tmp_list) + { + organization_t* organization_info = (organization_t*)tmp_list->data; + + _free_organization_info(q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info); + + q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info = g_new0(organization_t, 1); + ADVANCED_CATCH_SET_ERROR((q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info->organization_name = g_strdup(organization_info->organization_name); + q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info->department = g_strdup(organization_info->department); + q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info->office = g_strdup(organization_info->office); + q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info->title = g_strdup(organization_info->title); + q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info->role = g_strdup(organization_info->role); + q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info->logo_uri = g_strdup(organization_info->logo_uri); + + ADVANCED_SVC_TRACE("title : %s", q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info->title); + _free_organization_info((organization_t*)tmp_list->data); + q_handle->result_set[q_handle->return_array_pos].contact_info->organization_list = g_list_next(tmp_list); + } + else + { + ADVANCED_CATCH_SET_ERROR(false, {}, QUERY_NO_RECORD, ("no record")); + } + } + break; + case DATATYPE_ANNIVERSARY : + { + GList* tmp_list = q_handle->result_set[q_handle->return_array_pos].contact_info->event_list; + if(tmp_list) + { + event_info_t* event_info = (event_info_t*)tmp_list->data; + + _free_anniversary_info(q_handle->result_set[q_handle->return_array_pos].contact_info->event_info); + + q_handle->result_set[q_handle->return_array_pos].contact_info->event_info = g_new0(event_info_t, 1); + ADVANCED_CATCH_SET_ERROR((q_handle->result_set[q_handle->return_array_pos].contact_info->event_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + q_handle->result_set[q_handle->return_array_pos].contact_info->event_info->type = g_strdup(event_info->type); + q_handle->result_set[q_handle->return_array_pos].contact_info->event_info->date = g_strdup(event_info->date); + q_handle->result_set[q_handle->return_array_pos].contact_info->event_info->label = g_strdup(event_info->label); + + ADVANCED_SVC_TRACE("date : %s", q_handle->result_set[q_handle->return_array_pos].contact_info->event_info->date); + _free_anniversary_info((event_info_t*)tmp_list->data); + q_handle->result_set[q_handle->return_array_pos].contact_info->event_list = g_list_next(tmp_list); + } + else + { + ADVANCED_CATCH_SET_ERROR(false, {}, QUERY_NO_RECORD, ("no record")); + } + } + break; + case DATATYPE_NAME : + q_handle->result_set[q_handle->return_array_pos].contact_info->get_name = true; + ADVANCED_CATCH_SET_ERROR(false, {}, QUERY_NO_NEXT_ROW, ("NOT MULTIPLE VALUE")); + break; + case DATATYPE_CATEGORY : + { + if((q_handle->extra_info & CATEGORIES) != 0 && q_handle->next_count > -1) + { + int contact_id = atoi(q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info->contact_id); + + if(q_handle->next_count != 0) + { + ADVANCED_CATCH_SET_ERROR(((q_handle->category_pos + q_handle->next_count) < q_handle->category_total_count), {}, QUERY_NO_RECORD, ("no record")); + ADVANCED_CATCH_SET_ERROR((q_handle->category[q_handle->category_pos + q_handle->next_count].sibling != false), {}, QUERY_NO_RECORD, ("no record")); + q_handle->category_pos = q_handle->category_pos + q_handle->next_count; + q_handle->next_count++; + return QUERY_SUCCESS; + }else + { +#if 1 + int high, low, j; + high = q_handle->category_total_count; + low = 0; + + while(high >= low) + { + j = ( low + high ) / 2; + + if(q_handle->category[j].contact_id > contact_id) + high = j - 1; + else if(q_handle->category[j].contact_id < contact_id) + low = j + 1; + else if(q_handle->category[j].contact_id == contact_id) + { + q_handle->category_pos = j; + q_handle->next_count++; + return QUERY_SUCCESS; + } + } +#else + for(i = 0; i < q_handle->category_total_count; i++) + { + if(q_handle->category[i].contact_id == contact_id) + { + q_handle->category_pos = i; + q_handle->next_count++; + return QUERY_SUCCESS; + } + } +#endif + } + } + q_handle->next_count = -1; + ADVANCED_CATCH_SET_ERROR(false, {}, QUERY_NO_RECORD, ("no record")); + } + break; + case DATATYPE_X_ATTRIBUTE : + { + GList* tmp_list = q_handle->result_set[q_handle->return_array_pos].contact_info->x_list; + if(tmp_list) + { + x_info_t* x_info = (x_info_t*)tmp_list->data; + + _free_x_info(q_handle->result_set[q_handle->return_array_pos].contact_info->x_info); + + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info = g_new0(x_info_t, 1); + ADVANCED_CATCH_SET_ERROR((q_handle->result_set[q_handle->return_array_pos].contact_info->x_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->datatype_id = x_info->datatype_id; + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data1 = g_strdup(x_info->data1); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data2 = g_strdup(x_info->data2); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data3 = g_strdup(x_info->data3); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data4 = g_strdup(x_info->data4); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data5 = g_strdup(x_info->data5); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data6 = g_strdup(x_info->data6); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data7 = g_strdup(x_info->data7); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data8 = g_strdup(x_info->data8); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data9 = g_strdup(x_info->data9); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data10 = g_strdup(x_info->data10); + + _free_x_info((x_info_t*)tmp_list->data); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_list = g_list_next(tmp_list); + } + else + { + ADVANCED_CATCH_SET_ERROR(false, {}, QUERY_NO_RECORD, ("no record")); + } + } + break; + default: + break; + } + + ADVANCED_SVC_TRACE("error_code : %d", error_code); + +CATCH: + return error_code; +} + +query_error _invalid_datatype_fetch_next_row(advanced_handle_t* handle, predefine_datatype datatype) +{ + query_error error_code = QUERY_SUCCESS; + ADVANCED_RETURN_VAL((handle->result_set[handle->return_array_pos].contact_info != NULL), {}, QUERY_NO_RECORD, ("CONTACT INFO IS NULL")); + + if(datatype == DATATYPE_INVALID) + { + if(handle->query_type == QUERY_TO_CONTACT) + { + ADVANCED_RETURN_VAL((handle->result_set[handle->return_array_pos].contact_info->get_raw_contact_info == false), {}, QUERY_NO_NEXT_ROW, ("NO ROW")); + }else if(handle->query_type == QUERY_TO_PERSON) + { + ADVANCED_RETURN_VAL((handle->result_set[handle->return_array_pos].contact_info->get_person_info == false), {}, QUERY_NO_NEXT_ROW, ("NO ROW")); + } + }else if(datatype == DATATYPE_NAME) + { + ADVANCED_RETURN_VAL((handle->result_set[handle->return_array_pos].contact_info->get_name == false), {}, QUERY_NO_NEXT_ROW, ("NO ROW")); + } + + return error_code; +} + +char* _get_person_attribute_value(advanced_handle_t* q_handle, contact_attribute_e attribute, query_error* error_code) +{ + char* value = NULL; + + switch(attribute) + { + case CONTACT_ID : + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->person_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->person_info->contact_id; + break; + case CONTACT_IS_FAVORITE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->person_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->person_info->is_favorite; + break; + case CONTACT_RINGTONE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->person_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->person_info->ringtone; + break; + case CONTACT_PHOTO_URI: + break; + case CONTACT_LAST_UPDATED_TIME_STAMP: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->person_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->person_info->last_updated_timestamp; + break; + case CONTACT_UID: + break; + case NAME_FIRST : + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->person_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->person_info->first_name; + break; + case NAME_MIDDLE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->person_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->person_info->middle_name; + break; + case NAME_LAST: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->person_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->person_info->last_name; + break; + case NAME_PREFIX: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->person_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->person_info->prefix; + break; + case NAME_PHONETIC: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->person_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->person_info->phonetic_name; + break; + case NAME_DISPLAY : + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->person_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->person_info->display_name; + break; + default: + break; + } + +CATCH: + return value; +} + +#define CTS_IMAGE_LOCATION "/opt/data/contacts-svc/img" +void _get_contact_image(int img_type, char* contact_id, char** img_path) +{ + DIR *dp; + struct dirent *file_info; + char tmp_path[1024]; + char dir[1024]; + int index = 0; + + index = atoi(contact_id); + + snprintf(dir, sizeof(dir), "%s/%d", CTS_IMAGE_LOCATION, index); + snprintf(tmp_path, sizeof(tmp_path), "%d.", img_type); + + dp = opendir(dir); + if(NULL == dp) + return; + + *img_path = NULL; + while((file_info = readdir(dp)) != NULL) + { + if(0 == strncmp(tmp_path, file_info->d_name, strlen(tmp_path))) { + snprintf(tmp_path, sizeof(tmp_path), "%s/%s", dir, file_info->d_name); + *img_path = strdup(tmp_path); + if(NULL == *img_path) { + closedir(dp); + return; + } + break; + } + } + closedir(dp); +} + +char* _get_x_attribute_value(advanced_handle_t* q_handle, contact_x_attribute_e attribute, query_error* error_code) +{ + char* value = NULL; + + switch(attribute) + { + case X_DATA1: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->x_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data1; + break; + case X_DATA2: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->x_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data2; + break; + case X_DATA3: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->x_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data3; + break; + case X_DATA4: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->x_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data4; + break; + case X_DATA5: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->x_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data5; + break; + case X_DATA6: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->x_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data6; + break; + case X_DATA7: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->x_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data7; + break; + case X_DATA8: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->x_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data8; + break; + case X_DATA9: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->x_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data9; + break; + case X_DATA10: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->x_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data10; + break; + default: + break; + } +CATCH: + return value; +} + +char* _get_attribute_value(advanced_handle_t* q_handle, contact_attribute_e attribute, query_error* error_code) +{ + char* value = NULL; + + switch(attribute) + { + case CONTACT_ID : + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info->contact_id; + break; + case CONTACT_UID: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info->uid; + break; + case ACCOUNT_ID : + { + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + if(q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info->account_id != NULL) + { + int int_value = 0; + int total_count = 0; + int_value = atoi(q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info->account_id); + + get_all_addressbook_id(&total_count); + + GList* tmp_list = g_addressbook_list; + while(tmp_list) + { + addressbook_list* info = (addressbook_list*)tmp_list->data; + if(int_value == info->addressbook_id) + { + memset(q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info->account_id, 0x00, 64); + sprintf(q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info->account_id, "%d", info->account_id); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info->account_id; + break; + } + tmp_list = g_list_next(tmp_list); + } + } + } + break; + case CONTACT_IS_FAVORITE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info->is_favorite; + break; + case CONTACT_RINGTONE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info->ringtone; + break; + case CONTACT_NOTE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info->note; + break; + case CONTACT_PHOTO_URI: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + if((q_handle->extra_info & CONTACT_PHOTO) != 0) + { + OBJ_FREE(q_handle->result_set[q_handle->return_array_pos].contact_info->photo_uri); + q_handle->result_set[q_handle->return_array_pos].contact_info->photo_uri = NULL; + _get_contact_image(0, q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info->contact_id, + &(q_handle->result_set[q_handle->return_array_pos].contact_info->photo_uri)); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->photo_uri; + } + break; + case CONTACT_LAST_UPDATED_TIME_STAMP: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->raw_contact_info->last_updated_time_stamp; + break; + case NAME_FIRST : + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->name_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->name_info->first_name; + break; + case NAME_MIDDLE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->name_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->name_info->middle_name; + break; + case NAME_LAST: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->name_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->name_info->last_name; + break; + case NAME_PREFIX: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->name_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->name_info->prefix; + break; + case NAME_PHONETIC: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->name_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->name_info->phonetic_name; + break; + case NAME_DISPLAY : + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->name_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->name_info->display_name; + break; + case NICKNAME_NAME: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->nick_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->nick_info->nick_name; + break; + case NUMBER_ADDRESS: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->num_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->num_info->number; + break; + case NUMBER_TYPES: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->num_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->num_info->number_type; + break; + case EMAIL_ADDRESS: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->email_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->email_info->email_addr; + break; + case EMAIL_TYPE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->email_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->email_info->email_type; + break; + case URL_ADDRESS: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->url_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->url_info->url_addr; + break; + case URL_TYPE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->url_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->url_info->url_type; + break; + case ADDRESS_COUNTRY: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->address_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->country; + break; + case ADDRESS_REGION: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->address_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->region; + break; + case ADDRESS_CITY: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->address_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->city; + break; + case ADDRESS_STREET: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->address_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->street; + break; + case ADDRESS_POSTAL_CODE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->address_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->postal_code; + break; + case ADDRESS_ADDITIONAL: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->address_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->addtional; + break; + case ADDRESS_TYPE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->address_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->address_info->type; + break; + case CATEGORY_INFO: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->category[q_handle->category_pos].name != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->category[q_handle->category_pos].name; + break; + case EVENT_DATE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->event_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->event_info->date; + break; + case EVENT_TYPE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->event_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->event_info->type; + break; + case ORGANIZATION_NAME: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info->organization_name; + break; + case ORGANIZATION_DEPARTMENT: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info->department; + break; + case ORGANIZATION_TITLE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info->title; + break; + case ORGANIZATION_ROLE: + ADVANCED_CATCH_SET_ERROR_POINTER((q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info != NULL), {}, QUERY_NO_RECORD, ("no data")); + value = q_handle->result_set[q_handle->return_array_pos].contact_info->organization_info->role; + break; + default: + break; + } + +CATCH: + return value; +} + +API char* query_get_attribute(ADVANCED_HANDLE handle, contact_attribute_e attribute, query_error* error_code) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, NULL, ("HANDLE IS NULL")); + ADVANCED_RETURN_VAL((attribute < ATTRIBUTE_MAX), {}, NULL, ("INVALID ATTRIBUTE")); + + char* value = NULL; + predefine_datatype tmp_datatype = DATATYPE_INVALID; + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + ADVANCED_SVC_TRACE("q_handle->return_array_pos : %d", q_handle->return_array_pos); + ADVANCED_RETURN_VAL((q_handle->return_array_pos < q_handle->total_result_set_count), {}, NULL, ("RESULT SET IS NULL")); + ADVANCED_RETURN_VAL((q_handle->result_set[q_handle->return_array_pos].contact_info != NULL), {}, NULL, ("CONTACT INFO IS NULL")); + + tmp_datatype = _convert_attribute_to_mimetype_id(attribute); + if(q_handle->current_datatype != tmp_datatype || tmp_datatype == DATATYPE_INVALID) + { + q_handle->current_datatype = tmp_datatype; + q_handle->next_count = 0; + q_handle->category_pos = 0; + *error_code = QUERY_SUCCESS; + + if(tmp_datatype == DATATYPE_INVALID || tmp_datatype == DATATYPE_NAME) + *error_code = _invalid_datatype_fetch_next_row(q_handle, tmp_datatype); + else + *error_code = fetch_next_row(handle); + + ADVANCED_CATCH_SET_ERROR_POINTER((*error_code == QUERY_SUCCESS), {}, *error_code, ("fetch next row ERROR")); + } + + if(q_handle->query_type == QUERY_TO_PERSON) + value = _get_person_attribute_value(q_handle, attribute, error_code); + + if(value == NULL) + value = _get_attribute_value(q_handle, attribute, error_code); + + ADVANCED_SVC_TRACE("%d : %s", attribute, value); + +CATCH: + return value; +} + +API query_error query_set_order_by(ADVANCED_HANDLE handle, contact_attribute_e attribute, order_e ordering) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + ADVANCED_RETURN_VAL((attribute < ATTRIBUTE_MAX), {}, QUERY_INVALID_ATTRIBUTE, ("INVALID CONTACT ATTRIBUTE")); + ADVANCED_RETURN_VAL((ordering <= DESC), {}, QUERY_INVALID_TYPE, ("INVALID CONTACT ORDERING")); + ADVANCED_RETURN_VAL((attribute != CONTACT_ID), {}, QUERY_SUCCESS, ("DEFAULT ORDER ATTRIBUTE")); + + char* column_name = NULL; + query_error error_code = QUERY_SUCCESS; + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + + if(q_handle->query_type == QUERY_TO_PERSON) + { + column_name = _convert_person_attribute_to_column_name(attribute); + } + + if(column_name == NULL) + { + column_name = _convert_attribute_to_column_name(attribute); + + predefine_datatype datatype = DATATYPE_INVALID; + datatype = _convert_attribute_to_mimetype_id(attribute); + q_handle->all_datatype_in_query = (q_handle->all_datatype_in_query | datatype); + q_handle->order_field = attribute; + } + + g_string_append_printf(q_handle->order, "%s", column_name); + + q_handle->ordering = ordering; + + if(ordering == ASC) + { + g_string_append_printf(q_handle->order, " %s", "ASC"); + }else if(ordering == DESC) + { + g_string_append_printf(q_handle->order, " %s", "DESC"); + } + + ADVANCED_SVC_TRACE("order : %s", q_handle->order->str); + return error_code; +} + +API query_error query_set_condition_append(ADVANCED_HANDLE handle, condition_type_e type) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + ADVANCED_RETURN_VAL((type < CONDITION_TYPE_MAX), {}, QUERY_INVALID_TYPE, ("INVALID CONDITION TYPE")); + query_error error_code = QUERY_SUCCESS; + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + char* type_string = NULL; + + if(type == AND) + q_handle->optimize_condition = false; + + type_string = _convert_condition_type_to_string(type); + g_string_append_printf (q_handle->condition_text, " %s ", type_string); + g_string_append_printf (q_handle->use_normal_field_key, " %s ", type_string); + g_string_append_printf(q_handle->use_contact_table_id, " %s ", type_string); + + return error_code; +} + +API query_error query_set_x_attribute(ADVANCED_HANDLE handle, int cts_custom_type_index, contact_x_attribute_e attribute) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + ADVANCED_RETURN_VAL((attribute < X_DATA_MAX), {}, QUERY_INVALID_ATTRIBUTE, ("INVALID X-ATTRIBUTE")); + + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + + char* column_name = NULL; + char* table_name = NULL; + query_error error_code = QUERY_SUCCESS; + char* loc = NULL; + projection_t* projection_info = NULL; + + ADVANCED_SVC_TRACE("x_attribute : %d", attribute); + + q_handle->x_attribute_list[attribute] = 1; + + column_name = _convert_x_attribute_to_column_name(attribute); + + projection_info = g_new0(projection_t, 1); + projection_info->field = g_strdup(column_name); + q_handle->projection = g_list_append(q_handle->projection, projection_info); + + error_code = _set_datatype_list_by_x_attribute(q_handle, cts_custom_type_index, attribute); + ADVANCED_CATCH_SET_ERROR((error_code == QUERY_SUCCESS), {}, QUERY_FAIL, ("X DATA_TYPE CONVERTING FAIL")); + + if(table_name == NULL) + table_name = _convert_x_attribute_to_table_name(attribute); + + if(q_handle->table_list->str[0] != '\0') + { + loc = strstr(q_handle->table_list->str, table_name); + if(loc == NULL) + g_string_append_printf(q_handle->table_list, ", %s", table_name); + } + else + { + g_string_append_printf(q_handle->table_list, "%s", table_name); + } + + tables_e table_type = _contact_table_name_to_table_type(table_name); + q_handle->query_table = q_handle->query_table | table_type; + + ADVANCED_SVC_TRACE("table list : %s", q_handle->table_list->str); + q_handle->all_datatype_in_query = (q_handle->all_datatype_in_query | DATATYPE_X_ATTRIBUTE); + +CATCH: + return error_code; +} + +API query_error query_set_x_condition(ADVANCED_HANDLE handle, int cts_custom_type_index, contact_x_attribute_e attribute, condition_e attr, const char* value) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + ADVANCED_RETURN_VAL((attribute < X_DATA_MAX), {}, QUERY_INVALID_ATTRIBUTE, ("INVALID X-ATTRIBUTE")); + ADVANCED_RETURN_VAL((attr < CONDITION_MAX), {}, QUERY_INVALID_TYPE, ("INVALID CONTACT CONDITION")); + + query_error error_code = QUERY_SUCCESS; + char* column_name = NULL; + char* condition = NULL; + char* table = NULL; + condition_table_t* table_info = NULL; + bool new_custom_type = false; + alias_key_e tmp_current_alias = ALIAS_INVALID; + + if(attr == EXISTS) + { + error_code = _set_exists_condition(handle, attribute); + return error_code; + } + ADVANCED_RETURN_VAL((value != NULL), {}, QUERY_NULL_PARAMETER, ("INVALID VALUE")); + + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + ADVANCED_RETURN_VAL((q_handle->condition_category == NULL), {}, QUERY_GROUP_CASE, ("GROUP QUERY CASE")); + + ADVANCED_SVC_TRACE("condition value : %s", value); + condition = _convert_condition_to_string(attr); + + column_name = _convert_x_attribute_to_condition_column_name(attribute); + table = _convert_x_attribute_to_table_name(attribute); + tables_e table_type = _contact_table_name_to_table_type(table); + q_handle->query_table = q_handle->query_table | table_type; + + if(q_handle->current_alias != ALIAS_INVALID) + { + GList* tmp_condition_list = q_handle->condition_list; + while(tmp_condition_list) + { + condition_list_t* tmp_info = (condition_list_t*)tmp_condition_list->data; + + if(tmp_info->datatype != cts_custom_type_index) + { + new_custom_type = true; + }else + { + new_custom_type = false; + tmp_current_alias = tmp_info->current_alias; + break; + } + tmp_condition_list = g_list_next(tmp_condition_list); + } + if(new_custom_type) + { + q_handle->current_alias++; + tmp_current_alias = q_handle->current_alias; + + table_info = g_new0(condition_table_t, 1); + table_info->alias = q_handle->current_alias; + table_info->table = g_strdup(table); + q_handle->condition_table_list = g_list_append(q_handle->condition_table_list, table_info); + } + }else + { + q_handle->current_alias++; + tmp_current_alias = q_handle->current_alias; + + table_info = g_new0(condition_table_t, 1); + table_info->alias = q_handle->current_alias; + table_info->table = g_strdup(table); + q_handle->condition_table_list = g_list_append(q_handle->condition_table_list, table_info); + } + + g_string_append_printf(q_handle->condition_text, "(%s.%s %s ? and %s.%s = %d)", + alias_key[tmp_current_alias], column_name, condition, alias_key[tmp_current_alias], condition_field_key[FIELD_DATA_DATATYPE_ID], cts_custom_type_index); + + condition_list_t* condition_info = NULL; + condition_info = g_new0(condition_list_t, 1); + condition_info->current_alias = tmp_current_alias; + condition_info->column_name = g_strdup(column_name); + condition_info->condition = g_strdup(condition); + condition_info->datatype = cts_custom_type_index; + + q_handle->condition_list = g_list_append(q_handle->condition_list, condition_info); + + condition_val_t* condition_txt = NULL; + condition_txt = g_new0(condition_val_t, 1); + condition_txt->value = g_strdup(value); + condition_txt->x_attribute = true; + q_handle->condition_value = g_list_append(q_handle->condition_value, condition_txt); + + q_handle->condition_datatype = q_handle->condition_datatype | DATATYPE_X_ATTRIBUTE; + + return error_code; +} + +query_error query_set_limit(ADVANCED_HANDLE handle, int window_size) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + + query_error error_code = QUERY_SUCCESS; + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + + q_handle->start_pos = 0; + q_handle->window_size = window_size; + +return error_code; +} + +query_error query_get_next_limit_result_set(ADVANCED_HANDLE handle, int window_size) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + ADVANCED_RETURN_VAL((window_size >= 0), {}, QUERY_INVALID_ATTRIBUTE, ("RETURN COUNT SHOULD BE POSITIVE VALUE")); + + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + query_error error_code = QUERY_SUCCESS; + + q_handle->start_pos = _free_for_limit_iter(q_handle); + ADVANCED_SVC_TRACE("q_handle->start_pos : %d", q_handle->start_pos); + + q_handle->limit_iter = true; + q_handle->total_result_set_count = 0; + q_handle->pos = -1; + q_handle->old_contact_id = 0; + q_handle->return_array_pos = 0; + ADVANCED_SVC_TRACE("q_handle->total_result_set_count : %d", q_handle->total_result_set_count); + + q_handle->result_set = NULL; + q_handle->window_size = window_size; + + error_code = query_get_result_contact(handle); + + return error_code; +} + +API query_error query_next_custom_type(ADVANCED_HANDLE handle) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + query_error error_code = QUERY_SUCCESS; + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + ADVANCED_RETURN_VAL((q_handle->result_set[q_handle->return_array_pos].contact_info != NULL), {}, QUERY_NO_RECORD, ("CONTACT INFO IS NULL")); + + q_handle->x_fetching = NEXT_ROW_FETCH; + + GList* tmp_list = q_handle->result_set[q_handle->return_array_pos].contact_info->x_list; + if(tmp_list) + { + x_info_t* x_info = (x_info_t*)tmp_list->data; + _free_x_info(q_handle->result_set[q_handle->return_array_pos].contact_info->x_info); + + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info = g_new0(x_info_t, 1); + ADVANCED_CATCH_SET_ERROR((q_handle->result_set[q_handle->return_array_pos].contact_info->x_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->datatype_id = x_info->datatype_id; + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data1 = g_strdup(x_info->data1); + + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data2 = g_strdup(x_info->data2); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data3 = g_strdup(x_info->data3); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data4 = g_strdup(x_info->data4); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data5 = g_strdup(x_info->data5); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data6 = g_strdup(x_info->data6); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data7 = g_strdup(x_info->data7); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data8 = g_strdup(x_info->data8); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data9 = g_strdup(x_info->data9); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->data10 = g_strdup(x_info->data10); + + _free_x_info((x_info_t*)tmp_list->data); + q_handle->result_set[q_handle->return_array_pos].contact_info->x_list = g_list_next(tmp_list); + } + else + { + ADVANCED_CATCH_SET_ERROR(false, {}, QUERY_NO_RECORD, ("no record")); + } + ADVANCED_SVC_TRACE("error_code : %d", error_code); + +CATCH: + return error_code; +} + +API char* query_get_x_attribute(ADVANCED_HANDLE handle, contact_x_attribute_e attribute, int* cts_custom_type_index, query_error* error_code) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, NULL, ("HANDLE IS NULL")); + ADVANCED_RETURN_VAL((attribute < X_DATA_MAX), {}, NULL, ("INVALID ATTRIBUTE")); + + char* value = NULL; + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + ADVANCED_SVC_TRACE("q_handle->return_array_pos : %d", q_handle->return_array_pos); + ADVANCED_RETURN_VAL((q_handle->return_array_pos < q_handle->total_result_set_count), {}, NULL, ("RESULT SET IS NULL")); + ADVANCED_RETURN_VAL((q_handle->result_set[q_handle->return_array_pos].contact_info != NULL), {}, NULL, ("CONTACT INFO IS NULL")); + + if(q_handle->x_fetching != NEXT_ROW_FETCH) + q_handle->x_fetching = INIT_FETCH; + + if(q_handle->x_fetching == INIT_FETCH) + { + *error_code = query_next_custom_type(handle); + ADVANCED_CATCH_SET_ERROR_POINTER((*error_code == QUERY_SUCCESS), {}, *error_code, ("query_next_custom_type ERROR ")); + } + + value = _get_x_attribute_value(q_handle, attribute, error_code); + ADVANCED_CATCH_SET_ERROR_POINTER((*error_code == QUERY_SUCCESS), {}, *error_code, ("ERROR ")); + + *cts_custom_type_index = q_handle->result_set[q_handle->return_array_pos].contact_info->x_info->datatype_id; + + ADVANCED_SVC_TRACE("*cts_custom_type_index : %d", *cts_custom_type_index); + ADVANCED_SVC_TRACE("value : %s", value); + +CATCH: + return value; +} + +API query_error query_set_condition_with_indices_begin(ADVANCED_HANDLE handle) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + query_error error_code = QUERY_SUCCESS; + + ADVANCED_RETURN_VAL((q_handle->condition_category == NULL), {}, QUERY_GROUP_CASE, ("GROUP QUERY CASE")); + + g_string_append_printf(q_handle->id_list, "("); + + return error_code; +} + +API query_error query_set_condition_with_indices_end(ADVANCED_HANDLE handle) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + + query_error error_code = QUERY_SUCCESS; + //predefine_datatype datatype = DATATYPE_INVALID; + //db_datatype db_datatype_id = DB_DATATYPE_INVALID; + char* column_name = NULL; + char* normal_column_name = NULL; + //char* condition = NULL; + char* table = NULL; + condition_table_t* table_info = NULL; + alias_key_e tmp_current_alias = ALIAS_INVALID; + + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + ADVANCED_RETURN_VAL((q_handle->condition_category == NULL), {}, QUERY_GROUP_CASE, ("GROUP QUERY CASE")); + + g_string_append_printf(q_handle->id_list, ")"); + + column_name = _convert_attribute_to_condition_column_name(CONTACT_ID); + normal_column_name = _convert_attribute_to_column_name(CONTACT_ID); + + table = _convert_attribute_to_table_name(CONTACT_ID); + + q_handle->current_alias++; + tmp_current_alias = q_handle->current_alias; + + table_info = g_new0(condition_table_t, 1); + table_info->alias = q_handle->current_alias; + table_info->table = g_strdup(table); + q_handle->condition_table_list = g_list_append(q_handle->condition_table_list, table_info); + + q_handle->optimize_condition = false; + g_string_append_printf(q_handle->use_contact_table_id, "(%s in %s)", field_key[FIELD_CONTACT_CONTACT_ID], q_handle->id_list->str); + g_string_append_printf(q_handle->use_normal_field_key, "(%s in %s)", normal_column_name, q_handle->id_list->str); + + g_string_append_printf(q_handle->condition_text, "(%s.%s in %s)", alias_key[tmp_current_alias], column_name, q_handle->id_list->str); + + condition_val_t* condition_txt = NULL; + condition_txt = g_new0(condition_val_t, 1); + + condition_txt->attribute = CONTACT_ID; + condition_txt->indices_filter = true; + + q_handle->condition_value = g_list_append(q_handle->condition_value, condition_txt); + + return error_code; +} + +API query_error query_set_condition_with_indices(ADVANCED_HANDLE handle, const char* contact_index) +{ + ADVANCED_RETURN_VAL((handle != NULL), {}, QUERY_HANDLE_NONE, ("HANDLE IS NULL")); + advanced_handle_t* q_handle = (advanced_handle_t*)handle; + query_error error_code = QUERY_SUCCESS; + + if(q_handle->is_first_id_in_list == false) + { + q_handle->is_first_id_in_list = true; + g_string_append_printf(q_handle->id_list, "%s", contact_index); + }else + { + g_string_append_printf(q_handle->id_list, ", %s", contact_index); + } + + return error_code; +} + +API int get_contact_version() +{ + char query[128] = {0, }; + int rc = -1; + stmt pStmt = NULL; + int ver = 0; + query_error error_code = QUERY_SUCCESS; + + error_code = _db_init(); + ADVANCED_CATCH_SET_ERROR((error_code == QUERY_SUCCESS), {}, QUERY_STATEMENT_FAIL, ("DATABASE INIT FAIL")); + + sprintf(query, "select max(ver) from cts_version"); + + pStmt = _query_prepare(query); + ADVANCED_CATCH_SET_ERROR((pStmt != NULL), {}, QUERY_STATEMENT_FAIL, ("database prepare fail")); + + rc = _query_step(pStmt); + ADVANCED_CATCH_SET_ERROR((rc == SQLITE_ROW), {}, QUERY_NO_RECORD, ("No record in database")); + + ver = _query_column_int(pStmt, 0); + ADVANCED_SVC_TRACE("get_contact_version :: ver : %d ", ver); + +CATCH: + _query_finalize(pStmt); + _db_finish(); + + return ver; +} + diff --git a/src/platform/Tizen/Contact/query-svc/query-type.h b/src/platform/Tizen/Contact/query-svc/query-type.h new file mode 100755 index 0000000..34bbc21 --- /dev/null +++ b/src/platform/Tizen/Contact/query-svc/query-type.h @@ -0,0 +1,638 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @file query-type.h + * @author JihwaPark (82-32-3016262, jh7979.park@samsung.com) + * @version 1.0(2010.10.05) + * @brief This file has internal structure and logging APIs + */ + + +#ifndef _QUERY_TYPE_H +#define _QUERY_TYPE_H + +#define LOG_TAG "QUERY_SVC" + +#include +#include +#include +#include +#include "glib.h" +#include + +#include +#include +#include +#include +#include + +#include "db-util.h" +#include "query-service.h" +#include + +#define PROJECTION_FIELD_LEN 64 + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +//#define ADVANCED_USE_DLOG_MESSAGE +//#define CHECK_PERFORMANCE + +#ifdef ADVANCED_USE_DLOG_MESSAGE +#define ADVANCED_SVC_TRACE(fmt, arg...) \ + SLOGD("\n[QUERY_SVC]%s %d: " fmt "", __FUNCTION__, __LINE__, ##arg); +#else +#define ADVANCED_SVC_TRACE(fmt, arg...) \ +// fprintf(stderr, "\n[QUERY_SVC]%s %d: " fmt "", __FUNCTION__, __LINE__, ##arg); +#endif + +#ifdef CHECK_PERFORMANCE +#define PERFORMANCE_TRACE(fmt, arg...) \ + fprintf(stderr, "\n[QUERY_SVC]%s %d: " fmt "", __FUNCTION__, __LINE__, ##arg); +#else +#define PERFORMANCE_TRACE(fmt, arg...) +#endif + +#define ADVANCED_SVC_ERROR_TRACE(fmt, arg...) \ + fprintf(stderr, "\n[AdvancedSvc]%s %d: " fmt "", __FUNCTION__, __LINE__, ##arg); + +#define ADVANCED_RETURN_VAL(eval, expr, ret_val, X)\ + if (!(eval)) \ + {\ + expr; \ + {ADVANCED_SVC_TRACE X;}\ + return ret_val;\ + } else {;} + +#define ADVANCED_CATCH_SET_ERROR(eval, expr, error_val, X) \ + if (!(eval)) \ + {\ + expr; \ + error_code = (error_val);\ + {ADVANCED_SVC_TRACE X;}\ + goto CATCH;\ + } else {;} + +#define ADVANCED_CATCH_SET_ERROR_POINTER(eval, expr, error_val, X) \ + if (!(eval)) \ + {\ + expr; \ + *error_code = (error_val);\ + {ADVANCED_SVC_TRACE X;}\ + goto CATCH;\ + } else {;} + +#define OBJ_FREE(obj) if(obj != NULL) { free(obj); \ + (obj) = NULL; \ +} +/****************************************************************************************************/ +/* GLOBAL STRUCTURE DECLARATION */ +/****************************************************************************************************/ +#define _TABLE_SQLITE_SEQ "sqlite_sequence" // auto generated table +#define QUERY_MAX_LEN 2048 +#define MAX_NUMBER_TYPE 14 +#define MAX_EMAIL_TYPE 3 +#define MAX_ADDRESS_TYPE 7 + +typedef enum +{ + EXTRA_INFO_TYPE_FIELD = 0, + EXTRA_INFO_TYPE_CONDITION, +}extra_info_type; + +typedef enum +{ + ALIAS_INVALID = 0, + ALIAS_A, + ALIAS_B, + ALIAS_C, + ALIAS_D, + ALIAS_E, + ALIAS_F, + ALIAS_G, + ALIAS_H, + ALIAS_I, + ALIAS_J, + ALIAS_K, + ALIAS_L, + ALIAS_M, + ALIAS_N, + ALIAS_O, + ALIAS_P, + ALIAS_Q, + ALIAS_R, + ALIAS_S, + ALIAS_T, + ALIAS_U, + ALIAS_V, + ALIAS_W, + ALIAS_X, + ALIAS_Y, + ALIAS_Z, + ALIAS_MAX +}alias_key_e; + +typedef enum +{ + DATATYPE_INVALID = 0x00000000, + DATATYPE_NAME = 0x00000001, + DATATYPE_NUMBER = 0x00000002, + DATATYPE_EMAIL = 0x00000004, + DATATYPE_URL = 0x00000008, + DATATYPE_NICK_NAME = 0x00000010, + DATATYPE_ADDRESS = 0x00000020, + DATATYPE_ORGANIZATION = 0x00000040, + DATATYPE_BIRTH_DAY = 0x00000080, + DATATYPE_ANNIVERSARY = 0x0000100, + DATATYPE_IM_ADDR = 0x0000200, +// DATATYPE_LBS_INFO = 0x00000400, + DATATYPE_CATEGORY = 0x00000800, + DATATYPE_X_ATTRIBUTE = 0x80000000, +}predefine_datatype; + +typedef enum +{ + DB_DATATYPE_INVALID = 0, + DB_DATATYPE_NAME, + DB_DATATYPE_ADDRESS, + DB_DATATYPE_IM, + DB_DATATYPE_URL, + DB_DATATYPE_EVENT, + DB_DATATYPE_ORGANIZATION, + DB_DATATYPE_NICK_NAME, + DB_DATATYPE_NUMBER, + DB_DATATYPE_EMAIL, + +// DB_DATATYPE_LBS_INFO, +// DB_DATATYPE_CATEGORY, + DB_DATATYPE_MAX = 100, +}db_datatype; + +typedef enum +{ + NONE = 0x00000000, + HOME = 0x00000001, + WORK = 0x00000002, + VOICE = 0x00000004, + FAX = 0x00000008, + MSG = 0x00000010, + CELL = 0x00000020, + PAGER = 0x00000040, + BBS = 0x00000080, + MODEM = 0x00000100, + CAR = 0x00000200, + ISDN = 0x00000400, + VIDEO = 0x00000800, + PCS = 0x00001000, +}number_type; + +static char* number_type_str[MAX_NUMBER_TYPE] = +{ + "NONE", + "HOME", + "WORK", + "VOICE", + "FAX", + "MSG", + "CELL", + "PAGER", + "BBS", + "MODEM", + "CAR", + "ISDN", + "VIDEO", + "PCS", +}; + +typedef enum +{ + EMAIL_TYPE_NONE = 0x00000000, + EMAIL_HOME = 0x00000001, + EMAIL_WORK = 0x00000002, +}email_type; + +static char* email_type_str[MAX_EMAIL_TYPE] = +{ + "NONE", + "HOME", + "WORK", +}; + +typedef enum +{ + URL_TYPE_NONE = 0, + URL_HOME, + URL_WORK, + URL_TYPE_MAX +}url_type; + +static char* url_type_str[URL_TYPE_MAX] = +{ + "NONE", + "HOME", + "WORK", +}; + +typedef enum +{ + EVENT_BIRTHDAY = 0, + EVENT_ANNIVERSARY, + EVENT_TYPE_MAX +}event_type; + +static char* event_type_str[EVENT_TYPE_MAX] = +{ + "BIRTHDAY", + "ANNIVERSARY", +}; + +typedef enum +{ + ADDRESS_TYPE_NONE = 0x00000000, + ADDRESS_TYPE_HOME = 0x00000001, + ADDRESS_TYPE_WORK = 0x00000002, + ADDRESS_TYPE_DOM = 0x00000004, + ADDRESS_TYPE_INTL = 0x00000008, + ADDRESS_TYPE_POSTAL = 0x00000010, + ADDRESS_TYPE_PARCEL = 0x00000020, +}address_type; + +static char* addr_type_str[MAX_ADDRESS_TYPE] = +{ + "NONE", + "HOME", + "WORK", + "DOM", + "INTL", + "POSTAL", + "PARCEL", +}; + +static char* is_favorite_str[2] = +{ + "FALSE", + "TRUE", +}; + +typedef enum +{ + NORMAL_CASE = 0, + ONLY_CONTACT_ID_FIELD, +}projection_type; + +typedef enum +{ + INVALID_TABLE_LIST = 0, + ONLY_PERSON, + ONLY_CONTACT, + ONLY_DATA, + JOIN_PERSON_DATA, + JOIN_CONTACT_DATA, + ONLY_DATA_FROM_PERSON_QUERY, +// JOIN_PERSON_CONTACT_DATA, +}target_table_e; + +typedef enum +{ + INVALID_TABLE = 0x00000000, + PERSON_TABLE = 0x00000001, + CONTACT_TABLE = 0x00000002, + DATA_TABLE = 0x00000004, +}tables_e; + +typedef struct +{ + char* contact_id; + char* is_self; + char* contact_id_for_name; + char* contact_id_for_photo; + char* contactid_for_ringtone; + char* prefix; + char* first_name; + char* middle_name; + char* last_name; + char* phonetic_name; + char* display_name; + char* photo_URI; + char* last_updated_timestamp; + char* is_favorite; + char* send_to_voicemail; + char* ringtone; +}person_contact_t; + +typedef struct +{ + char* contact_id; + char* ringtone; + char* note; + char* is_favorite; + char* photo_uri; + char* birth_day; + char* last_updated_time_stamp; + char* read_only; + char* send_to_voice_mail; + char* latitude; + char* longitude; + char* account_id; + char* uid; +}raw_contact_t; + +typedef struct +{ + char* first_name; + char* middle_name; + char* last_name; + char* prefix; + char* phonetic_name; + char* display_name; +}name_t; + +typedef struct +{ + char* nick_name; +}nick_name_t; + +typedef struct +{ + char* number; + char* number_type; + char* number_label; // not use +}number_t; + +typedef struct +{ + char* email_addr; + char* email_type; + char* email_label; // not use +}email_t; + +typedef struct +{ + char* url_addr; + char* url_type; + char* url_label; // not use +}url_t; + +typedef struct +{ + char* country; + char* region; + char* county; + char* city; + char* street; + char* postal_code; + char* addtional; + char* type; +}address_t; + +typedef struct +{ + char* organization_name; + char* department; + char* office; + char* title; + char* role; + char* logo_uri; +}organization_t; + +typedef struct +{ + char* type; + char* date; + char* label; +}event_info_t; + +typedef struct +{ + char* category; +}category_t; + +typedef struct +{ + int datatype_id; + char* data1; + char* data2; + char* data3; + char* data4; + char* data5; + char* data6; + char* data7; + char* data8; + char* data9; + char* data10; +}x_info_t; + +typedef struct +{ + person_contact_t* person_info; + raw_contact_t* raw_contact_info; + name_t* name_info; + + char* photo_uri; + + GList* nickname_list; + GList* number_list; + GList* email_list; + GList* url_list; + GList* address_list; + GList* organization_list; + GList* event_list; + GList* category_list; + GList* x_list; + + nick_name_t* nick_info; + number_t* num_info; + email_t* email_info; + url_t* url_info; + address_t* address_info; + organization_t* organization_info; + event_info_t* event_info; + x_info_t* x_info; + + bool get_name; + bool get_raw_contact_info; + bool get_person_info; +}contact_t; + +typedef struct +{ + bool is_occupied; + contact_t* contact_info; +}result_t; + +typedef struct +{ + db_datatype datatype; + char* field; +}datatype_t; + +typedef struct +{ + char* field; +}projection_t; + +typedef struct +{ + int ordered_pos; +}ordering_list_t; + +typedef struct +{ + int contact_id; +}mapping_list_t; + +typedef struct +{ + contact_attribute_e attribute; + int int_value; + double real_value; + char* value; + bool x_attribute; + bool indices_filter; +}condition_val_t; + +typedef struct +{ + alias_key_e alias; + char* table; +}condition_table_t; + +typedef struct +{ + alias_key_e current_alias; + char* column_name; + char* condition; + db_datatype datatype; +}condition_list_t; + +typedef struct +{ + char* name; +}condition_category_t; + + +typedef struct +{ + int group_id; + int contact_id; + char* name; + bool sibling; +}categories_info; + +typedef enum +{ + INVALID_FIELDS = 0x00000000, + CONTACT_PHOTO = 0x00000001, + CATEGORIES = 0x00000002 +}extra_contact_info; + +typedef sqlite3_stmt* stmt; + +typedef enum +{ + INIT_FETCH = 0, + NEXT_ROW_FETCH, +}fetching_state; + +typedef struct +{ + query_type_e query_type; + stmt hstmt; + +// result set + int pos; //array index of ordering list + bool is_optimized_query; + +// query + predefine_datatype assigned_datatype; + GList* datatype_list; + + GList* projection; + GList* new_projection; //use making result set + + GString* table_list; + tables_e query_table; + target_table_e join_table; + + char* query_string; + + result_t* result_set; + int old_contact_id; + mapping_list_t* mapping_id_to_result_set; + + extra_contact_info extra_info; + categories_info* category; + int category_total_count; + int next_count; + int category_pos; + int attribute_list[ATTRIBUTE_MAX]; + int x_attribute_list[X_DATA_MAX]; + +// especially for query to person + int person_field; + +// set condition + GString* condition_text; + GString* use_normal_field_key; + GString* use_contact_table_id; + GList* condition_value; + alias_key_e current_alias; + predefine_datatype condition_datatype; + bool optimize_condition; + GList* condition_list; + GList* condition_table_list; + char* condition_category; + char* condition_category_op; + + extra_contact_info condition_extra_info; + +// set order by + ordering_list_t* ordering_list; + GString* order; + contact_attribute_e order_field; + order_e ordering; + mapping_list_t* full_ordered_contact_id; + int total_count; + +// set limit + int start_pos; + int window_size; + bool limit_iter; + +// the others + int total_result_set_count; + int return_array_pos; + predefine_datatype current_datatype; + +// performance + predefine_datatype all_datatype_in_query; + +// x-attribute + fetching_state x_fetching; + +// indices + GString* id_list; + bool is_first_id_in_list; +}advanced_handle_t; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif // _QUERY_TYPE_H + diff --git a/src/platform/Tizen/Contact/query-svc/query-utility.c b/src/platform/Tizen/Contact/query-svc/query-utility.c new file mode 100755 index 0000000..add93d5 --- /dev/null +++ b/src/platform/Tizen/Contact/query-svc/query-utility.c @@ -0,0 +1,2003 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @file query-utility.c + * @author JihwaPark (82-32-3016262, jh7979.park@samsung.com) + * @version 1.0(2011.10.05) + * @brief This file serves utility for advanced query. + */ + +#include "query-service.h" +#include "query-type.h" +#include "query-utility.h" +#include +#include +#include + +static int transaction_count = 0; +static int db_connnect_count = 0; + +clock_t +_get_clock() +{ + long curtime; + + struct timeval tv; + gettimeofday(&tv, NULL); + curtime = tv.tv_sec * 1000000 + tv.tv_usec; + + return curtime; +} + +bool +_print_time(clock_t begin, clock_t finish, const char* function_name) +{ + double totaltime = 0.0; + totaltime=(double) (finish-begin)/CLOCKS_PER_SEC; + + PERFORMANCE_TRACE("......................................................................... "); + PERFORMANCE_TRACE("TEST CASE [%s] ", function_name); +// PERFORMANCE_TRACE("start time [%ld us] ", begin); +// PERFORMANCE_TRACE("finish time [%ld us] ", finish); + PERFORMANCE_TRACE("total time [%f s] ", totaltime); + PERFORMANCE_TRACE("......................................................................... "); + + return true; +} + +query_error _db_init() +{ + int rc = 0; + query_error error_code = QUERY_SUCCESS; + + db_connnect_count++; + if(!g_hDBCt) + { + rc = db_util_open(QUERY_DB_PATH, &g_hDBCt, 0); + if(rc != SQLITE_OK) + error_code = QUERY_FAIL; + } + return error_code; +} + +query_error _db_finish() +{ + int rc = 0; + query_error error_code = QUERY_SUCCESS; + + db_connnect_count--; + if(db_connnect_count == 0) + { + rc = db_util_close(g_hDBCt); + if(rc != SQLITE_OK) + error_code = QUERY_FAIL; + else + g_hDBCt = NULL; + } + return error_code; +} + +query_error _exec_query(char* query) +{ + int rc = -1; + char* pszErrorMsg = NULL; + query_error error_code = QUERY_SUCCESS; + + ADVANCED_SVC_TRACE("query : %s", query); + + rc = sqlite3_exec(g_hDBCt, query, NULL, NULL, &pszErrorMsg); + + if(SQLITE_OK != rc) + { + ADVANCED_SVC_TRACE("contact_util_query_exec failed(%d).\n", rc); + error_code = QUERY_FAIL; + } + + if(pszErrorMsg) + sqlite3_free(pszErrorMsg); + + return error_code; +} + +query_error _trans_begin(void) +{ + int rc = -1; + query_error error_code = QUERY_SUCCESS; + + if(transaction_count == 0) + { + rc = _exec_query("BEGIN IMMEDIATE TRANSACTION"); + if(SQLITE_OK != rc) + { + ADVANCED_SVC_TRACE("contact_util_query_exec failed(%d).\n", rc); + return QUERY_FAIL; + } + } + transaction_count++; + ADVANCED_SVC_TRACE("contact transaction_count : %d.\n", transaction_count); + + return error_code; +} + +query_error _trans_end(bool is_success) +{ + int rc = -1; + query_error error_code = QUERY_SUCCESS; + + if(transaction_count == 1) + { + if(is_success == true) + rc = _exec_query("COMMIT TRANSACTION"); + else + rc = _exec_query("ROLLBACK TRANSACTION"); + + if(SQLITE_OK != rc) + { + ADVANCED_SVC_TRACE("contact_util_query_exec failed(%d).\n", rc); + return QUERY_FAIL; + } + + } + transaction_count--; + + if(transaction_count < 0) + transaction_count = 0; + + ADVANCED_SVC_TRACE("contact transaction_count : %d.\n", transaction_count); + + return error_code; +} + + +int _query_step(stmt pStmt) +{ + return sqlite3_step(pStmt); +} + +void _contact_query_finalize(stmt pStmt) +{ + int rc = -1; + + if(!pStmt) + return; + + rc = sqlite3_finalize(pStmt); + if(rc != SQLITE_OK) + { + } +} + +int _contact_query_column_int(stmt pStmt, int pos) +{ + return (int)sqlite3_column_int(pStmt, pos); +} + +char* _contact_query_column_text(stmt pStmt, int pos) +{ + return (char *)sqlite3_column_text(pStmt, pos); +} + +void _query_finalize(stmt pStmt) +{ + int rc = -1; + + if(!pStmt) + return; + + rc = sqlite3_finalize(pStmt); + if(rc != SQLITE_OK) + { + + } +} + +int _query_bind_double(stmt pStmt, int pos, double num) +{ + return sqlite3_bind_double(pStmt, pos, num); +} + +int _query_bind_int(stmt pStmt, int pos, int num) +{ + return sqlite3_bind_int(pStmt, pos, num); +} + +int _query_bind_text(stmt pStmt, int pos, char* str) +{ + int len = 0; + if(str != NULL) + { + len = strlen(str); + return sqlite3_bind_text(pStmt, pos, (const char*)str, len, SQLITE_STATIC); + } + return -1; +} + +void _query_stmt_reset(stmt stmt) +{ + sqlite3_reset(stmt); + sqlite3_clear_bindings(stmt); +} + +int _query_column_int(stmt pStmt, int pos) +{ + return sqlite3_column_int(pStmt, pos); +} + +double _query_column_double(stmt pStmt, int pos) +{ + return sqlite3_column_double(pStmt, pos); +} + +char* _query_column_text(stmt pStmt, int pos) +{ + return (char *)sqlite3_column_text(pStmt, pos); +} + +stmt _query_prepare(char *query) +{ + int rc = -1; + stmt pStmt = NULL; + + ADVANCED_SVC_TRACE("query : %s !!!!\n", query); +// printf("\nquery : %s !!!!\n", query); + + rc = sqlite3_prepare_v2(g_hDBCt, query, strlen(query), &pStmt, NULL); + if(SQLITE_OK != rc) + { + ADVANCED_SVC_TRACE("rc : %d", rc); + return NULL; + } + + return pStmt; +} + +bool _convert_person_attribute_to_mimetype_id(contact_attribute_e attribute) +{ + bool is_person_attr = false; + + switch(attribute) + { + case NAME_FIRST : + case NAME_MIDDLE: + case NAME_LAST: + case NAME_PREFIX: + case NAME_PHONETIC: + is_person_attr = true; + break; + default: + is_person_attr = false; + } + ADVANCED_SVC_TRACE("is_person_attr : %d", is_person_attr); + + return is_person_attr; +} + +predefine_datatype _convert_attribute_to_mimetype_id(contact_attribute_e attribute) +{ + predefine_datatype data_type = DATATYPE_INVALID; + switch(attribute) + { + case NAME_FIRST : + case NAME_MIDDLE: + case NAME_LAST: + case NAME_PREFIX: + case NAME_PHONETIC: + case NAME_DISPLAY: + data_type = DATATYPE_NAME; + break; + case NICKNAME_NAME: + data_type = DATATYPE_NICK_NAME; + break; + case NUMBER_ADDRESS: + case NUMBER_TYPES: + data_type = DATATYPE_NUMBER; + break; + case EMAIL_ADDRESS: + case EMAIL_TYPE: + data_type = DATATYPE_EMAIL; + break; + case URL_ADDRESS: + case URL_TYPE: + data_type = DATATYPE_URL; + break; + case EVENT_DATE: + case EVENT_TYPE: + data_type = DATATYPE_ANNIVERSARY; + break; +/* + case ANNIVERSARY_LABEL: + data_type = DATATYPE_ANNIVERSARY; + break; + case CONTACT_LATITUDE: + case CONTACT_LONGITUDE: + data_type = DATATYPE_LBS_INFO; + break; +*/ + case ADDRESS_COUNTRY: + case ADDRESS_REGION: +// case ADDRESS_COUNTY: + case ADDRESS_CITY: + case ADDRESS_STREET: + case ADDRESS_POSTAL_CODE: + case ADDRESS_ADDITIONAL: + case ADDRESS_TYPE: + data_type = DATATYPE_ADDRESS; + break; + case CATEGORY_INFO: + data_type = DATATYPE_CATEGORY; + break; + case ORGANIZATION_NAME: + case ORGANIZATION_DEPARTMENT: +// case ORGANIZATION_OFFICE: + case ORGANIZATION_TITLE: + case ORGANIZATION_ROLE: +// case ORGANIZATION_LOGO_URI: + data_type = DATATYPE_ORGANIZATION; + break; + case CONTACT_IS_FAVORITE: + case CONTACT_RINGTONE: + case CONTACT_NOTE: +// case CONTACT_READ_ONLY: +// case CONTACT_SEND_TO_VOICE_MAIL: + case CONTACT_LAST_UPDATED_TIME_STAMP: + case CONTACT_ID : + case CONTACT_UID : + case ACCOUNT_ID : + default: + break; + } + + ADVANCED_SVC_TRACE("data_type : %d", data_type); + + return data_type; +} + +char* _convert_person_attribute_to_condition_column_name(contact_attribute_e attribute) +{ + char* field_name = NULL; + + switch(attribute) + { + case CONTACT_ID : + field_name = condition_field_key[FIELD_PERSON_CONTACT_ID]; + break; + case CONTACT_IS_FAVORITE : + field_name = condition_field_key[FIELD_PERSON_IS_FAVORITE]; + break; + case CONTACT_RINGTONE : + field_name = condition_field_key[FIELD_PERSON_RINGTONE]; + break; +// case CONTACT_PHOTO_URI : +// field_name = condition_field_key[FIELD_PERSON_PHOTO_URI]; +// break; +// case CONTACT_SEND_TO_VOICE_MAIL : +// field_name = condition_field_key[FIELD_PERSON_SEND_TO_VOICEMAIL]; +// break; + case NAME_FIRST : + field_name = condition_field_key[FIELD_PERSON_FIRST_NAME]; + break; + case NAME_MIDDLE : + field_name = condition_field_key[FIELD_PERSON_MIDDLE_NAME]; + break; + case NAME_LAST : + field_name = condition_field_key[FIELD_PERSON_LAST_NAME]; + break; + case NAME_PREFIX : + field_name = condition_field_key[FIELD_PERSON_PREFIX_NAME]; + break; + case NAME_PHONETIC : + field_name = condition_field_key[FIELD_PERSON_PHONETIC_NAME]; + break; + case NAME_DISPLAY : + field_name = condition_field_key[FIELD_PERSON_DISPLAY_NAME]; + break; + default : + break; + } + return field_name; +} + +char* _convert_person_attribute_to_column_name(contact_attribute_e attribute) +{ + char* field_name = NULL; + + switch(attribute) + { + case CONTACT_ID : + field_name = field_key[FIELD_PERSON_CONTACT_ID]; + break; + case CONTACT_IS_FAVORITE : + field_name = field_key[FIELD_PERSON_IS_FAVORITE]; + break; + case CONTACT_RINGTONE : + field_name = field_key[FIELD_PERSON_RINGTONE]; + break; +// case CONTACT_PHOTO_URI : +// field_name = field_key[FIELD_PERSON_PHOTO_URI]; +// break; +// case CONTACT_SEND_TO_VOICE_MAIL : +// field_name = field_key[FIELD_PERSON_SEND_TO_VOICEMAIL]; +// break; + case NAME_FIRST : + field_name = field_key[FIELD_PERSON_FIRST_NAME]; + break; + case NAME_MIDDLE : + field_name = field_key[FIELD_PERSON_MIDDLE_NAME]; + break; + case NAME_LAST : + field_name = field_key[FIELD_PERSON_LAST_NAME]; + break; + case NAME_PREFIX : + field_name = field_key[FIELD_PERSON_PREFIX_NAME]; + break; + case NAME_PHONETIC : + field_name = field_key[FIELD_PERSON_PHONETIC_NAME]; + break; + case NAME_DISPLAY : + field_name = field_key[FIELD_PERSON_DISPLAY_NAME]; + break; + default : + break; + } + return field_name; +} + +char* _convert_attribute_to_condition_normalize_column(contact_attribute_e attribute) +{ + char* field_name = NULL; + + switch(attribute) + { + case NAME_DISPLAY: + field_name = condition_field_key[FIELD_DATA8]; + break; + default: + break; + } + return field_name; +} + +char* _convert_attribute_to_normalize_column(contact_attribute_e attribute) +{ + char* field_name = NULL; + + switch(attribute) + { + case NAME_DISPLAY: + field_name = field_key[FIELD_DATA8]; + break; + default: + break; + } + return field_name; +} + +char* _convert_attribute_to_condition_column_name(contact_attribute_e attribute) +{ + char* field_name = NULL; + + switch(attribute) + { + case CONTACT_RINGTONE : + field_name = condition_field_key[FIELD_RINGTONE]; + break; + case CONTACT_NOTE : + field_name = condition_field_key[FIELD_NOTE]; + break; + case CONTACT_ID : + field_name = condition_field_key[FIELD_DATA_CONTACT_ID]; + break; + case CONTACT_UID : + field_name = condition_field_key[FIELD_UID]; + break; + case ACCOUNT_ID : + field_name = condition_field_key[FIELD_CONTACT_ACCOUNT_ID]; + break; + case CONTACT_IS_FAVORITE : + field_name = condition_field_key[FIELD_IS_FAVORITE]; + break; +// case CONTACT_PHOTO_URI : +// field_name = condition_field_key[FIELD_PHOTO_URI]; +// break; + case CONTACT_LAST_UPDATED_TIME_STAMP : + field_name = condition_field_key[FIELD_CHANGED_TIME]; + break; +// case CONTACT_READ_ONLY : +// field_name = condition_field_key[FIELD_DATA_CONTACT_ID]; +// break; +// case CONTACT_SEND_TO_VOICE_MAIL : +// field_name = condition_field_key[FIELD_DATA_CONTACT_ID]; +// break; +// case CONTACT_LATITUDE : +// field_name = condition_field_key[FIELD_DATA1]; +// break; +// case CONTACT_LONGITUDE : +// field_name = condition_field_key[FIELD_DATA2]; +// break; + case NAME_FIRST : + field_name = condition_field_key[FIELD_DATA2]; + break; + case NAME_LAST: + field_name = condition_field_key[FIELD_DATA3]; + break; + case NAME_MIDDLE: + field_name = condition_field_key[FIELD_DATA4]; + break; + case NAME_DISPLAY: + field_name = condition_field_key[FIELD_DATA5]; + break; + case NAME_PREFIX: + field_name = condition_field_key[FIELD_DATA6]; + break; + case NAME_PHONETIC: + field_name = condition_field_key[FIELD_DATA7]; + break; + case NICKNAME_NAME: + field_name = condition_field_key[FIELD_DATA2]; + break; + case NUMBER_ADDRESS: + field_name = condition_field_key[FIELD_DATA2]; + break; + case NUMBER_TYPES: + field_name = condition_field_key[FIELD_DATA1]; + break; + case EMAIL_ADDRESS: + field_name = condition_field_key[FIELD_DATA2]; + break; + case EMAIL_TYPE: + field_name = condition_field_key[FIELD_DATA1]; + break; + case URL_ADDRESS: + field_name = condition_field_key[FIELD_DATA2]; + break; + case URL_TYPE: + field_name = condition_field_key[FIELD_DATA1]; + break; + case ADDRESS_COUNTRY: + field_name = condition_field_key[FIELD_DATA8]; + break; + case ADDRESS_REGION: + field_name = condition_field_key[FIELD_DATA4]; + break; +// case ADDRESS_COUNTY: +// field_name = condition_field_key[FIELD_DATA5]; +// break; + case ADDRESS_CITY: + field_name = condition_field_key[FIELD_DATA5]; + break; + case ADDRESS_STREET: + field_name = condition_field_key[FIELD_DATA6]; + break; + case ADDRESS_POSTAL_CODE: + field_name = condition_field_key[FIELD_DATA3]; + break; + case ADDRESS_ADDITIONAL: + field_name = condition_field_key[FIELD_DATA7]; + break; + case ADDRESS_TYPE: + field_name = condition_field_key[FIELD_DATA1]; + break; +// case CATEGORY_INFO: +// field_name = condition_field_key[FIELD_DATA1]; +// break; + case EVENT_TYPE: + field_name = condition_field_key[FIELD_DATA1]; + break; + case EVENT_DATE: + field_name = condition_field_key[FIELD_DATA2]; + break; +// case ANNIVERSARY_LABEL: +// field_name = condition_field_key[FIELD_DATA2]; +// break; + case ORGANIZATION_NAME: + field_name = condition_field_key[FIELD_DATA2]; + break; + case ORGANIZATION_DEPARTMENT: + field_name = condition_field_key[FIELD_DATA3]; + break; +// case ORGANIZATION_OFFICE: +// field_name = condition_field_key[FIELD_DATA3]; +// break; + case ORGANIZATION_TITLE: + field_name = condition_field_key[FIELD_DATA4]; + break; + case ORGANIZATION_ROLE: + field_name = condition_field_key[FIELD_DATA5]; + break; +// case ORGANIZATION_LOGO_URI: +// field_name = condition_field_key[FIELD_DATA6]; +// break; + default: + break; + } + ADVANCED_SVC_TRACE("field_name : %s", field_name); + + return field_name; +} + +primitive_type _convert_check_attribute_primitive_type(contact_attribute_e attribute) +{ + primitive_type type = INTEGER; + + switch(attribute) + { + case CONTACT_ID : + case ACCOUNT_ID : +// case CONTACT_READ_ONLY : +// case CONTACT_SEND_TO_VOICE_MAIL : + case CONTACT_LAST_UPDATED_TIME_STAMP : + case CONTACT_IS_FAVORITE : + case NUMBER_TYPES: + case EMAIL_TYPE: + case URL_TYPE: + case ADDRESS_TYPE: + case EVENT_TYPE: + type = INTEGER; + break; +// case CONTACT_LATITUDE : +// case CONTACT_LONGITUDE : +// type = REAL; +// break; + case CONTACT_UID : + case CONTACT_RINGTONE : + case CONTACT_NOTE : +// case CONTACT_PHOTO_URI : + case NAME_FIRST : + case NAME_LAST: + case NAME_MIDDLE: + case NAME_DISPLAY: + case NAME_PREFIX: + case NAME_PHONETIC: + case NICKNAME_NAME: + case NUMBER_ADDRESS: + case EMAIL_ADDRESS: + case URL_ADDRESS: + case ADDRESS_COUNTRY: + case ADDRESS_REGION: +// case ADDRESS_COUNTY: + case ADDRESS_CITY: + case ADDRESS_STREET: + case ADDRESS_POSTAL_CODE: + case ADDRESS_ADDITIONAL: +// case CATEGORY_INFO: + case EVENT_DATE: +// case ANNIVERSARY_LABEL: + case ORGANIZATION_NAME: + case ORGANIZATION_DEPARTMENT: +// case ORGANIZATION_OFFICE: + case ORGANIZATION_TITLE: + case ORGANIZATION_ROLE: +// case ORGANIZATION_LOGO_URI: + type = STRING; + break; + default: + break; + } + ADVANCED_SVC_TRACE("primitive type : %d", type); + + return type; +} + +char* _convert_x_attribute_to_condition_column_name(contact_x_attribute_e attribute) +{ + char* field_name = NULL; + + switch(attribute) + { + case X_DATA1 : + field_name = condition_x_field_key[FIELD_X_DATA1]; + break; + case X_DATA2 : + field_name = condition_x_field_key[FIELD_X_DATA2]; + break; + case X_DATA3: + field_name = condition_x_field_key[FIELD_X_DATA3]; + break; + case X_DATA4: + field_name = condition_x_field_key[FIELD_X_DATA4]; + break; + case X_DATA5: + field_name = condition_x_field_key[FIELD_X_DATA5]; + break; + case X_DATA6: + field_name = condition_x_field_key[FIELD_X_DATA6]; + break; + case X_DATA7: + field_name = condition_x_field_key[FIELD_X_DATA7]; + break; + case X_DATA8: + field_name = condition_x_field_key[FIELD_X_DATA8]; + break; + case X_DATA9: + field_name = condition_x_field_key[FIELD_X_DATA9]; + break; + case X_DATA10: + field_name = condition_x_field_key[FIELD_X_DATA10]; + break; + default: + break; + } + ADVANCED_SVC_TRACE("field_name : %s", field_name); + + return field_name; +} + +char* _convert_attribute_to_column_name(contact_attribute_e attribute) +{ + char* field_name = NULL; + + switch(attribute) + { + case CONTACT_RINGTONE : + field_name = field_key[FIELD_RINGTONE]; + break; + case CONTACT_NOTE : + field_name = field_key[FIELD_NOTE]; + break; + case CONTACT_UID : + field_name = field_key[FIELD_UID]; + break; + case CONTACT_ID : + field_name = field_key[FIELD_DATA_CONTACT_ID]; + break; + case ACCOUNT_ID : + field_name = field_key[FIELD_CONTACT_ACCOUNT_ID]; + break; + case CONTACT_IS_FAVORITE : + field_name = field_key[FIELD_IS_FAVORITE]; + break; +// case CONTACT_PHOTO_URI : +// field_name = field_key[FIELD_PHOTO_URI]; +// break; + case CONTACT_LAST_UPDATED_TIME_STAMP : + field_name = field_key[FIELD_CHANGED_TIME]; + break; +// case CONTACT_READ_ONLY : +// field_name = field_key[FIELD_DATA_CONTACT_ID]; +// break; +// case CONTACT_SEND_TO_VOICE_MAIL : +// field_name = field_key[FIELD_DATA_CONTACT_ID]; +// break; +/* + case CONTACT_LATITUDE : + field_name = field_key[FIELD_DATA1]; + break; + case CONTACT_LONGITUDE : + field_name = field_key[FIELD_DATA2]; + break; +*/ + case NAME_FIRST : + field_name = field_key[FIELD_DATA2]; + break; + case NAME_LAST: + field_name = field_key[FIELD_DATA3]; + break; + case NAME_MIDDLE: + field_name = field_key[FIELD_DATA4]; + break; + case NAME_DISPLAY: + field_name = field_key[FIELD_DATA5]; + break; + case NAME_PREFIX: + field_name = field_key[FIELD_DATA6]; + break; + case NAME_PHONETIC: + field_name = field_key[FIELD_DATA7]; + break; + case NICKNAME_NAME: + field_name = field_key[FIELD_DATA2]; + break; + case NUMBER_ADDRESS: + field_name = field_key[FIELD_DATA2]; + break; + case NUMBER_TYPES: + field_name = field_key[FIELD_DATA1]; + break; + case EMAIL_ADDRESS: + field_name = field_key[FIELD_DATA1]; + break; + case EMAIL_TYPE: + field_name = field_key[FIELD_DATA2]; + break; + case URL_ADDRESS: + field_name = field_key[FIELD_DATA1]; + break; + case URL_TYPE: + field_name = field_key[FIELD_DATA2]; + break; + case ADDRESS_COUNTRY: + field_name = field_key[FIELD_DATA8]; + break; + case ADDRESS_REGION: + field_name = field_key[FIELD_DATA4]; + break; +// case ADDRESS_COUNTY: +// field_name = field_key[FIELD_DATA5]; +// break; + case ADDRESS_CITY: + field_name = field_key[FIELD_DATA5]; + break; + case ADDRESS_STREET: + field_name = field_key[FIELD_DATA6]; + break; + case ADDRESS_POSTAL_CODE: + field_name = field_key[FIELD_DATA3]; + break; + case ADDRESS_ADDITIONAL: + field_name = field_key[FIELD_DATA7]; + break; + case ADDRESS_TYPE: + field_name = field_key[FIELD_DATA1]; + break; +// case CATEGORY_INFO: +// field_name = field_key[FIELD_DATA1]; +// break; + case EVENT_TYPE: + field_name = field_key[FIELD_DATA1]; + break; + case EVENT_DATE: + field_name = field_key[FIELD_DATA2]; + break; +// case ANNIVERSARY_LABEL: +// field_name = field_key[FIELD_DATA2]; +// break; + case ORGANIZATION_NAME: + field_name = field_key[FIELD_DATA2]; + break; + case ORGANIZATION_DEPARTMENT: + field_name = field_key[FIELD_DATA3]; + break; +// case ORGANIZATION_OFFICE: +// field_name = field_key[FIELD_DATA3]; +// break; + case ORGANIZATION_TITLE: + field_name = field_key[FIELD_DATA4]; + break; + case ORGANIZATION_ROLE: + field_name = field_key[FIELD_DATA5]; + break; +// case ORGANIZATION_LOGO_URI: +// field_name = field_key[FIELD_DATA6]; +// break; + default: + break; + } +// ADVANCED_SVC_TRACE("field_name : %s", field_name); + + return field_name; +} + +char* _convert_x_attribute_to_column_name(contact_x_attribute_e attribute) +{ + char* field_name = NULL; + + switch(attribute) + { + case X_DATA1 : + field_name = x_field_key[FIELD_X_DATA1]; + break; + case X_DATA2 : + field_name = x_field_key[FIELD_X_DATA2]; + break; + case X_DATA3 : + field_name = x_field_key[FIELD_X_DATA3]; + break; + case X_DATA4 : + field_name = x_field_key[FIELD_X_DATA4]; + break; + case X_DATA5 : + field_name = x_field_key[FIELD_X_DATA5]; + break; + case X_DATA6 : + field_name = x_field_key[FIELD_X_DATA6]; + break; + case X_DATA7 : + field_name = x_field_key[FIELD_X_DATA7]; + break; + case X_DATA8 : + field_name = x_field_key[FIELD_X_DATA8]; + break; + case X_DATA9 : + field_name = x_field_key[FIELD_X_DATA9]; + break; + case X_DATA10 : + field_name = x_field_key[FIELD_X_DATA10]; + break; + default: + break; + } + ADVANCED_SVC_TRACE("field_name : %s", field_name); + + return field_name; +} + +tables_e _contact_table_name_to_table_type(char* table_name) +{ + tables_e table_type = INVALID_TABLE; + + if(strcmp(table_name, table_key[TABLE_CONTACT]) == 0) + table_type = CONTACT_TABLE; + else if(strcmp(table_name, table_key[TABLE_DATA]) == 0) + table_type = DATA_TABLE; + else if(strcmp(table_name, table_key[TABLE_PERSON]) == 0) + table_type = PERSON_TABLE; + + return table_type; +} + +char* _convert_person_attribute_to_table_name(contact_attribute_e attribute) +{ + char* table_name = NULL; + switch(attribute) + { +// case CONTACT_PHOTO_URI: +// case CONTACT_READ_ONLY: +// case CONTACT_SEND_TO_VOICE_MAIL: + case CONTACT_LAST_UPDATED_TIME_STAMP: + case CONTACT_IS_FAVORITE: + case CONTACT_RINGTONE : + case CONTACT_ID: + case NAME_FIRST : + case NAME_MIDDLE: + case NAME_LAST: + case NAME_PHONETIC: + case NAME_PREFIX: + case NAME_DISPLAY: + { + table_name = table_key[TABLE_PERSON]; + } + break; + default: + break; + } + + ADVANCED_SVC_TRACE("table_name : %s", table_name); + + return table_name; +} + +char* _convert_attribute_to_table_name(contact_attribute_e attribute) +{ + char* table_name = NULL; + switch(attribute) + { +// case CONTACT_PHOTO_URI: +// case CONTACT_READ_ONLY: +// case CONTACT_SEND_TO_VOICE_MAIL: + case CONTACT_LAST_UPDATED_TIME_STAMP: + case CONTACT_IS_FAVORITE: + case CONTACT_RINGTONE : + case CONTACT_NOTE : + case ACCOUNT_ID: + case CONTACT_UID: + { + table_name = table_key[TABLE_CONTACT]; + } + break; + case CONTACT_ID: +// case CONTACT_LATITUDE: +// case CONTACT_LONGITUDE: + case NAME_FIRST : + case NAME_MIDDLE: + case NAME_LAST: + case NAME_PHONETIC: + case NAME_PREFIX: + case NAME_DISPLAY: + case NICKNAME_NAME: + case NUMBER_ADDRESS: + case NUMBER_TYPES: + case EMAIL_ADDRESS: + case EMAIL_TYPE: + case URL_ADDRESS: + case URL_TYPE: + case ADDRESS_COUNTRY: + case ADDRESS_REGION: +// case ADDRESS_COUNTY: + case ADDRESS_CITY: + case ADDRESS_STREET: + case ADDRESS_POSTAL_CODE: + case ADDRESS_ADDITIONAL: + case ADDRESS_TYPE: +// case CATEGORY_INFO: + case EVENT_DATE: + case EVENT_TYPE: +// case ANNIVERSARY_LABEL: + case ORGANIZATION_NAME: + case ORGANIZATION_DEPARTMENT: +// case ORGANIZATION_OFFICE: + case ORGANIZATION_TITLE: + case ORGANIZATION_ROLE: +// case ORGANIZATION_LOGO_URI: + { + table_name = table_key[TABLE_DATA]; + } + break; + default: + break; + } + +// ADVANCED_SVC_TRACE("table_name : %s", table_name); + return table_name; +} + +char* _convert_x_attribute_to_table_name(contact_x_attribute_e attribute) +{ + char* table_name = NULL; + table_name = table_key[TABLE_DATA]; + + return table_name; +} + +char* _convert_condition_type_to_string(condition_type_e type) +{ + char* string = NULL; + + switch(type) + { + case LEFT_BRACKET : + { + string = condition_type_key[0]; + } + break; + case RIGHT_BRACKET: + { + string = condition_type_key[1]; + } + break; + case AND: + { + string = condition_type_key[2]; + } + break; + case OR: + { + string = condition_type_key[3]; + } + break; + default: + break; + } + + ADVANCED_SVC_TRACE("condition type string : %s", string); + + return string; +} + +void _query_get_count(const char* table_name, query_type_e query_type, int* count) +{ + char query[128] = {0, }; + int rc = -1; + stmt pStmt = NULL; + + *count = 0; + + memset(query, 0x00, sizeof(query)); + + switch(query_type) + { + case QUERY_TO_PERSON: + snprintf(query, sizeof(query) - 1, "select count(%s) from %s", field_key[FIELD_PERSON_CONTACT_ID], table_name); + break; + case QUERY_TO_CONTACT: + { + if(strcmp(table_key[TABLE_PRESENCE], table_name) == 0) + snprintf(query, sizeof(query) - 1, "select count(%s) from %s", field_key[FIELD_PRESENCE_CONTACT_ID], table_name); + else if(strcmp(table_key[TABLE_CONTACT], table_name) == 0) + snprintf(query, sizeof(query) - 1, "select count(%s) from %s", field_key[FIELD_CONTACT_CONTACT_ID], table_name); + else if(strcmp(table_key[TABLE_GROUP_RELATION], table_name) == 0) + snprintf(query, sizeof(query) - 1, "select count(%s) from %s", relation_field_key[FIELD_GROUP_RELATION_CONTACT_ID], table_name); + } + break; + default: + break; + } + ADVANCED_SVC_TRACE("query : %s", query); + + rc = sqlite3_prepare_v2(g_hDBCt, query, strlen(query), &pStmt, NULL); + + rc = sqlite3_step(pStmt); + if(SQLITE_ROW == rc) + *count = sqlite3_column_int(pStmt, 0); + + if(*count < 0) + *count = 0; + ADVANCED_SVC_TRACE("*count : %d", *count); + + sqlite3_finalize(pStmt); +} + +void __free_datatype_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_datatype_list"); +// ADVANCED_SVC_TRACE("datatype : %d", ((datatype_t*)data)->datatype); + OBJ_FREE(((datatype_t*)data)->field); + OBJ_FREE(data); +} + +void __free_condition_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_condition_list"); +// ADVANCED_SVC_TRACE("field : %s", ((datatype_t*)data)->field); + OBJ_FREE(((condition_list_t*)data)->column_name); + OBJ_FREE(((condition_list_t*)data)->condition); + OBJ_FREE(data); +} + +void __free_condition_table_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_condition_table_list"); +// ADVANCED_SVC_TRACE("field : %s", ((datatype_t*)data)->field); + OBJ_FREE(((condition_table_t*)data)->table); + OBJ_FREE(data); +} + +void __free_projection_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_projection_list"); +// ADVANCED_SVC_TRACE("field : %s", ((datatype_t*)data)->field); + OBJ_FREE(((projection_t*)data)->field); + OBJ_FREE(data); +} + +void __free_condition_value_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_condition_value_list"); +// ADVANCED_SVC_TRACE("field : %s", ((condition_val_t*)data)->value); + OBJ_FREE(((condition_val_t*)data)->value); + OBJ_FREE(data); +} + +void __free_email_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_email_list"); + OBJ_FREE(((email_t*)data)->email_addr); + OBJ_FREE(((email_t*)data)->email_type); + OBJ_FREE(((email_t*)data)->email_label); + OBJ_FREE(data); +} + +void __free_number_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_email_list"); + OBJ_FREE(((number_t*)data)->number); + OBJ_FREE(((number_t*)data)->number_type); + OBJ_FREE(((number_t*)data)->number_label); + OBJ_FREE(data); +} + +void __free_url_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_url_list"); + OBJ_FREE(((url_t*)data)->url_addr); + OBJ_FREE(((url_t*)data)->url_type); + OBJ_FREE(((url_t*)data)->url_label); + OBJ_FREE(data); +} + +void __free_nickname_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_nickname_list"); + OBJ_FREE(((nick_name_t*)data)->nick_name); + OBJ_FREE(data); +} + +void __free_address_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_address_list"); + OBJ_FREE(((address_t*)data)->country); + OBJ_FREE(((address_t*)data)->region); + OBJ_FREE(((address_t*)data)->county); + OBJ_FREE(((address_t*)data)->city); + OBJ_FREE(((address_t*)data)->street); + OBJ_FREE(((address_t*)data)->postal_code); + OBJ_FREE(((address_t*)data)->addtional); + OBJ_FREE(((address_t*)data)->type); + OBJ_FREE(data); +} + +void __free_organization_list(gpointer data, gpointer user_data) +{ + if(data == NULL) + return; + ADVANCED_SVC_TRACE("__free_organization_list"); + OBJ_FREE(((organization_t*)data)->organization_name); + OBJ_FREE(((organization_t*)data)->department); + OBJ_FREE(((organization_t*)data)->office); + OBJ_FREE(((organization_t*)data)->title); + OBJ_FREE(((organization_t*)data)->role); + OBJ_FREE(((organization_t*)data)->logo_uri); + OBJ_FREE(data); +} + +void __free_anniversary_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_anniversary_list"); + OBJ_FREE(((event_info_t*)data)->date); + OBJ_FREE(((event_info_t*)data)->label); + OBJ_FREE(data); +} + +void __free_category_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_category_list"); + OBJ_FREE(((category_t*)data)->category); + OBJ_FREE(data); +} + +void __free_x_list(gpointer data, gpointer user_data) +{ + ADVANCED_SVC_TRACE("__free_x_list"); + OBJ_FREE(((x_info_t*)data)->data2); + OBJ_FREE(((x_info_t*)data)->data3); + OBJ_FREE(((x_info_t*)data)->data4); + OBJ_FREE(((x_info_t*)data)->data5); + OBJ_FREE(((x_info_t*)data)->data6); + OBJ_FREE(((x_info_t*)data)->data7); + OBJ_FREE(((x_info_t*)data)->data8); + OBJ_FREE(((x_info_t*)data)->data9); + OBJ_FREE(((x_info_t*)data)->data10); + OBJ_FREE(data); +} + +void _free_x_info(x_info_t* x_info) +{ + if(x_info == NULL) + return; + + OBJ_FREE(x_info->data2); + OBJ_FREE(x_info->data3); + OBJ_FREE(x_info->data4); + OBJ_FREE(x_info->data5); + OBJ_FREE(x_info->data6); + OBJ_FREE(x_info->data7); + OBJ_FREE(x_info->data8); + OBJ_FREE(x_info->data9); + OBJ_FREE(x_info->data10); + OBJ_FREE(x_info); +} + +void _free_category_info(categories_info* category_info) +{ + if(category_info == NULL) + return; + + OBJ_FREE(category_info->name); + OBJ_FREE(category_info); +} + +void _free_name_info(name_t* name_info) +{ + if(name_info == NULL) + return; + + OBJ_FREE(name_info->first_name); + OBJ_FREE(name_info->middle_name); + OBJ_FREE(name_info->last_name); + OBJ_FREE(name_info->prefix); + OBJ_FREE(name_info->phonetic_name); + OBJ_FREE(name_info->display_name); + OBJ_FREE(name_info); +} + +void _free_raw_contact_info(raw_contact_t* raw_contact_info) +{ + if(raw_contact_info == NULL) + return; + + OBJ_FREE(raw_contact_info->contact_id); + OBJ_FREE(raw_contact_info->ringtone); + OBJ_FREE(raw_contact_info->note); + OBJ_FREE(raw_contact_info->is_favorite); + OBJ_FREE(raw_contact_info->photo_uri); + OBJ_FREE(raw_contact_info->birth_day); + OBJ_FREE(raw_contact_info->last_updated_time_stamp); + OBJ_FREE(raw_contact_info->read_only); + OBJ_FREE(raw_contact_info->send_to_voice_mail); + OBJ_FREE(raw_contact_info->latitude); + OBJ_FREE(raw_contact_info->longitude); + OBJ_FREE(raw_contact_info->account_id); + OBJ_FREE(raw_contact_info->uid); + OBJ_FREE(raw_contact_info); +} + +void _free_person_contact_info(person_contact_t* person_info) +{ + if(person_info == NULL) + return; + + OBJ_FREE(person_info->contact_id); + OBJ_FREE(person_info->is_self); + OBJ_FREE(person_info->contact_id_for_name); + OBJ_FREE(person_info->contact_id_for_photo); + OBJ_FREE(person_info->contactid_for_ringtone); + OBJ_FREE(person_info->prefix); + OBJ_FREE(person_info->first_name); + OBJ_FREE(person_info->middle_name); + OBJ_FREE(person_info->last_name); + OBJ_FREE(person_info->phonetic_name); + OBJ_FREE(person_info->display_name); + OBJ_FREE(person_info->photo_URI); + OBJ_FREE(person_info->last_updated_timestamp); + OBJ_FREE(person_info->is_favorite); + OBJ_FREE(person_info->send_to_voicemail); + OBJ_FREE(person_info->ringtone); + OBJ_FREE(person_info); +} + +void _free_num_info(number_t* num_info) +{ + if(num_info == NULL) + return; + + OBJ_FREE(num_info->number); + OBJ_FREE(num_info->number_type); + OBJ_FREE(num_info->number_label); + OBJ_FREE(num_info); +} + +void _free_email_info(email_t* email_info) +{ + if(email_info == NULL) + return; + + OBJ_FREE(email_info->email_addr); + OBJ_FREE(email_info->email_type); + OBJ_FREE(email_info->email_label); + OBJ_FREE(email_info); +} + +void _free_url_info(url_t* url_info) +{ + if(url_info == NULL) + return; + + OBJ_FREE(url_info->url_addr); + OBJ_FREE(url_info->url_type); + OBJ_FREE(url_info->url_label); + OBJ_FREE(url_info); +} + +void _free_nick_info(nick_name_t* nick_info) +{ + if(nick_info == NULL) + return; + + OBJ_FREE(nick_info->nick_name); + OBJ_FREE(nick_info); +} + +void _free_anniversary_info(event_info_t* event_info) +{ + if(event_info == NULL) + return; + + OBJ_FREE(event_info->date); + OBJ_FREE(event_info->label); + OBJ_FREE(event_info); +} + +void _free_organization_info(organization_t* organization_info) +{ + if(organization_info == NULL) + return; + + OBJ_FREE(organization_info->organization_name); + OBJ_FREE(organization_info->department); + OBJ_FREE(organization_info->office); + OBJ_FREE(organization_info->title); + OBJ_FREE(organization_info->role); + OBJ_FREE(organization_info->logo_uri); + OBJ_FREE(organization_info); +} + +void _free_address_info(address_t* address_info) +{ + if(address_info == NULL) + return; + + OBJ_FREE(address_info->country); + OBJ_FREE(address_info->region); + OBJ_FREE(address_info->county); + OBJ_FREE(address_info->city); + OBJ_FREE(address_info->street); + OBJ_FREE(address_info->postal_code); + OBJ_FREE(address_info->addtional); + OBJ_FREE(address_info->type); + OBJ_FREE(address_info); +} + +void _free_projection_list(gpointer data, gpointer user_data) +{ +// ADVANCED_SVC_TRACE("__free_projection_list"); +// ADVANCED_SVC_TRACE("field : %s", ((projection_t*)data)->field); + OBJ_FREE(((projection_t*)data)->field); + OBJ_FREE(data); +} + +db_datatype _convert_datatype_to_db_type(predefine_datatype datatype) +{ + db_datatype db_datatype_id = DB_DATATYPE_INVALID; + + switch(datatype) + { + case DATATYPE_NAME: + db_datatype_id = DB_DATATYPE_NAME; + break; + case DATATYPE_NUMBER: + db_datatype_id = DB_DATATYPE_NUMBER; + break; + case DATATYPE_EMAIL: + db_datatype_id = DB_DATATYPE_EMAIL; + break; + case DATATYPE_URL: + db_datatype_id = DB_DATATYPE_URL; + break; + case DATATYPE_NICK_NAME: + db_datatype_id = DB_DATATYPE_NICK_NAME; + break; + case DATATYPE_ADDRESS: + db_datatype_id = DB_DATATYPE_ADDRESS; + break; + case DATATYPE_ORGANIZATION: + db_datatype_id = DB_DATATYPE_ORGANIZATION; + break; + case DATATYPE_BIRTH_DAY: + db_datatype_id = DB_DATATYPE_EVENT; + break; + case DATATYPE_ANNIVERSARY: + db_datatype_id = DB_DATATYPE_EVENT; + break; +/* + case DATATYPE_LBS_INFO: + db_datatype_id = DB_DATATYPE_LBS_INFO; + break; + case DATATYPE_CATEGORY: + db_datatype_id = DB_DATATYPE_CATEGORY; + break; +*/ + default: + break; + } + + return db_datatype_id; +} + +query_error _set_person_datatype_list(advanced_handle_t* q_handle, contact_attribute_e attribute) +{ + query_error error_code = QUERY_SUCCESS; + + predefine_datatype datatype = DATATYPE_INVALID; + datatype_t* datatype_info = NULL; + + datatype = _convert_attribute_to_mimetype_id(attribute); + ADVANCED_CATCH_SET_ERROR(((q_handle->assigned_datatype & datatype) == DATATYPE_INVALID), {}, QUERY_SUCCESS, ("DUPLICATED DATATYPE")); + + datatype_info = g_new0(datatype_t, 1); + ADVANCED_CATCH_SET_ERROR((datatype_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + datatype_info->field = g_strdup(field_key[FIELD_DATA_DATATYPE_ID]); + + datatype_info->datatype = _convert_datatype_to_db_type(datatype); + q_handle->datatype_list = g_list_append(q_handle->datatype_list, datatype_info); + q_handle->assigned_datatype = (q_handle->assigned_datatype | datatype); + q_handle->all_datatype_in_query = (q_handle->all_datatype_in_query | datatype); + + ADVANCED_SVC_TRACE("q_handle->assigned_datatype : %d", q_handle->assigned_datatype); + +CATCH: + return error_code; +} + +query_error _set_datatype_list(advanced_handle_t* q_handle, contact_attribute_e attribute) +{ + query_error error_code = QUERY_SUCCESS; + + predefine_datatype datatype = DATATYPE_INVALID; + datatype_t* datatype_info = NULL; + + datatype = _convert_attribute_to_mimetype_id(attribute); + ADVANCED_CATCH_SET_ERROR((datatype != DATATYPE_INVALID), {}, QUERY_INVALID_ATTRIBUTE, ("INVALID ATTRIBUTE")); + ADVANCED_CATCH_SET_ERROR(((q_handle->assigned_datatype & datatype) == DATATYPE_INVALID), {}, QUERY_SUCCESS, ("DUPLICATED DATATYPE")); + + datatype_info = g_new0(datatype_t, 1); + ADVANCED_CATCH_SET_ERROR((datatype_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + datatype_info->field = g_strdup(field_key[FIELD_DATA_DATATYPE_ID]); + + datatype_info->datatype = _convert_datatype_to_db_type(datatype); + q_handle->datatype_list = g_list_append(q_handle->datatype_list, datatype_info); + q_handle->assigned_datatype = (q_handle->assigned_datatype | datatype); + q_handle->all_datatype_in_query = (q_handle->all_datatype_in_query | datatype); + +// ADVANCED_SVC_TRACE("q_handle->assigned_datatype : %d", q_handle->assigned_datatype); + +CATCH: + return error_code; +} + +query_error _set_datatype_list_by_x_attribute(advanced_handle_t* q_handle, int datatype_id, contact_x_attribute_e attribute) +{ + query_error error_code = QUERY_SUCCESS; + datatype_t* datatype_info = NULL; + + GList* tmp_list = q_handle->datatype_list; + while(tmp_list) + { + datatype_t* tmp_info = (datatype_t*)tmp_list->data; + ADVANCED_CATCH_SET_ERROR((tmp_info->datatype != datatype_id), {}, QUERY_SUCCESS, ("DUPLICATED DATATYPE")); + tmp_list = g_list_next(tmp_list); + } + + datatype_info = g_new0(datatype_t, 1); + ADVANCED_CATCH_SET_ERROR((datatype_info != NULL), {}, QUERY_ALLOCATE_MEMORY_FAIL, ("ALLOCATION FAIL")); + datatype_info->field = g_strdup(field_key[FIELD_DATA_DATATYPE_ID]); + + datatype_info->datatype = datatype_id; + q_handle->datatype_list = g_list_append(q_handle->datatype_list, datatype_info); + q_handle->assigned_datatype = (q_handle->assigned_datatype | DATATYPE_X_ATTRIBUTE); + q_handle->all_datatype_in_query = (q_handle->all_datatype_in_query | DATATYPE_X_ATTRIBUTE); + + ADVANCED_SVC_TRACE("q_handle->assigned_datatype : %d", q_handle->assigned_datatype); + +CATCH: + return error_code; +} + +char* _convert_condition_to_string(condition_e condition) +{ + char* condition_val = NULL; + + switch(condition) + { + case EQUAL : + { + condition_val = condition_key[EQUAL]; + } + break; + case NOT_EQUAL: + { + condition_val = condition_key[NOT_EQUAL]; + } + break; + case GREATER_THAN: + { + condition_val = condition_key[GREATER_THAN]; + } + break; + case LESS_THAN: + { + condition_val = condition_key[LESS_THAN]; + } + break; + case GREATER_THAN_OR_EQUAL: + { + condition_val = condition_key[GREATER_THAN_OR_EQUAL]; + } + break; + case LESS_THAN_OR_EQUAL: + { + condition_val = condition_key[LESS_THAN_OR_EQUAL]; + } + break; + case LIKE: + { + condition_val = condition_key[LIKE]; + } + break; + default: + break; + } + ADVANCED_SVC_TRACE("condition_val : %s", condition_val); + + return condition_val; +} + +void _free_handle_info(advanced_handle_t* handle) +{ + if(handle == NULL) + { + ADVANCED_SVC_TRACE("HANDLE IS ALREAD FREE"); + return; + } + + int i = 0; + +// Free Glist + g_list_foreach(handle->datatype_list, __free_datatype_list, NULL); + g_list_foreach(handle->new_projection, __free_projection_list, NULL); + g_list_foreach(handle->condition_value, __free_condition_value_list, NULL); + g_list_foreach(handle->condition_list, __free_condition_list, NULL); + g_list_foreach(handle->condition_table_list, __free_condition_table_list, NULL); + + g_list_free(handle->datatype_list); + g_list_free(handle->new_projection); + g_list_free(handle->condition_value); + g_list_free(handle->condition_list); + g_list_free(handle->condition_table_list); + +// Free g_string + g_string_free (handle->table_list, TRUE); + g_string_free (handle->condition_text, TRUE); + g_string_free (handle->use_normal_field_key, TRUE); + g_string_free (handle->use_contact_table_id, TRUE); + g_string_free (handle->order, TRUE); + g_string_free (handle->id_list, TRUE); + +// free result set + for(i = 0; i < handle->total_result_set_count; i++) + { + g_list_foreach(handle->result_set[i].contact_info->number_list, __free_number_list, NULL); + g_list_foreach(handle->result_set[i].contact_info->email_list, __free_email_list, NULL); + + g_list_foreach(handle->result_set[i].contact_info->url_list, __free_url_list, NULL); + g_list_foreach(handle->result_set[i].contact_info->nickname_list, __free_nickname_list, NULL); + g_list_foreach(handle->result_set[i].contact_info->address_list, __free_address_list, NULL); + g_list_foreach(handle->result_set[i].contact_info->organization_list, __free_organization_list, NULL); + g_list_foreach(handle->result_set[i].contact_info->event_list, __free_anniversary_list, NULL); + g_list_foreach(handle->result_set[i].contact_info->category_list, __free_category_list, NULL); + g_list_foreach(handle->result_set[i].contact_info->x_list, __free_x_list, NULL); + + g_list_free(handle->result_set[i].contact_info->url_list); + g_list_free(handle->result_set[i].contact_info->nickname_list); + g_list_free(handle->result_set[i].contact_info->address_list); + g_list_free(handle->result_set[i].contact_info->organization_list); + g_list_free(handle->result_set[i].contact_info->event_list); + g_list_free(handle->result_set[i].contact_info->category_list); + g_list_free(handle->result_set[i].contact_info->x_list); + + _free_person_contact_info(handle->result_set[i].contact_info->person_info); + _free_raw_contact_info(handle->result_set[i].contact_info->raw_contact_info); + + _free_name_info(handle->result_set[i].contact_info->name_info); + _free_num_info(handle->result_set[i].contact_info->num_info); + _free_email_info(handle->result_set[i].contact_info->email_info); + _free_url_info(handle->result_set[i].contact_info->url_info); + _free_nick_info(handle->result_set[i].contact_info->nick_info); + _free_address_info(handle->result_set[i].contact_info->address_info); + _free_organization_info(handle->result_set[i].contact_info->organization_info); + _free_anniversary_info(handle->result_set[i].contact_info->event_info); + _free_x_info(handle->result_set[i].contact_info->x_info); + + OBJ_FREE(handle->result_set[i].contact_info->photo_uri); + OBJ_FREE(handle->result_set[i].contact_info); + } + + OBJ_FREE(handle->result_set); + + for(i = 0; i < handle->total_result_set_count; i++) + { + OBJ_FREE(handle->mapping_id_to_result_set); + } + + for(i = 0; i < handle->total_result_set_count; i++) + { + OBJ_FREE(handle->ordering_list); + } + + _free_category_info(handle->category); + + OBJ_FREE(handle->query_string); + OBJ_FREE(handle->ordering_list); + OBJ_FREE(handle->full_ordered_contact_id); + OBJ_FREE(handle->condition_category); + OBJ_FREE(handle->condition_category_op); + OBJ_FREE(handle); +} + +int _free_for_limit_iter(advanced_handle_t* handle) +{ + int i = 0; + int id = 0; + char* contact_id = NULL; + +// free result set + for(i = 0; i < handle->total_result_set_count; i++) + { + if(handle->result_set[i].contact_info->raw_contact_info) + { + contact_id = handle->result_set[i].contact_info->raw_contact_info->contact_id; + id = atoi(contact_id); + ADVANCED_SVC_TRACE("id : %d", id); + } + + if(handle->result_set[i].contact_info->person_info) + { + contact_id = handle->result_set[i].contact_info->person_info->contact_id; + if(handle->result_set[i].contact_info->person_info->contact_id) + id = atoi(contact_id); + } + + g_list_foreach(handle->result_set[i].contact_info->number_list, __free_number_list, NULL); + g_list_foreach(handle->result_set[i].contact_info->email_list, __free_email_list, NULL); + + g_list_foreach(handle->result_set[i].contact_info->url_list, __free_url_list, NULL); + g_list_foreach(handle->result_set[i].contact_info->nickname_list, __free_nickname_list, NULL); + g_list_foreach(handle->result_set[i].contact_info->address_list, __free_address_list, NULL); + g_list_foreach(handle->result_set[i].contact_info->organization_list, __free_organization_list, NULL); + g_list_foreach(handle->result_set[i].contact_info->event_list, __free_anniversary_list, NULL); + g_list_foreach(handle->result_set[i].contact_info->category_list, __free_category_list, NULL); + + _free_person_contact_info(handle->result_set[i].contact_info->person_info); + _free_raw_contact_info(handle->result_set[i].contact_info->raw_contact_info); + + _free_name_info(handle->result_set[i].contact_info->name_info); + _free_num_info(handle->result_set[i].contact_info->num_info); + _free_email_info(handle->result_set[i].contact_info->email_info); + _free_url_info(handle->result_set[i].contact_info->url_info); + _free_nick_info(handle->result_set[i].contact_info->nick_info); + _free_address_info(handle->result_set[i].contact_info->address_info); + _free_organization_info(handle->result_set[i].contact_info->organization_info); + _free_anniversary_info(handle->result_set[i].contact_info->event_info); + + OBJ_FREE(handle->result_set[i].contact_info); + } + OBJ_FREE(handle->result_set); + + for(i = 0; i < handle->total_result_set_count; i++) + OBJ_FREE(handle->mapping_id_to_result_set); + + for(i = 0; i < handle->total_result_set_count; i++) + OBJ_FREE(handle->ordering_list); + + return id; +} + +query_error _normalize_str(const char* src, char* dest, int dest_size) +{ + query_error error_code = QUERY_SUCCESS; + + int32_t size = 0; + UErrorCode status = 0; + UChar* tmp_result = NULL; + UChar* result = NULL; + + tmp_result = g_new0(UChar, (dest_size + 1)); + result = g_new0(UChar, (dest_size + 1)); + + u_strFromUTF8(tmp_result, dest_size, NULL, src, -1, &status); + ADVANCED_CATCH_SET_ERROR((U_FAILURE(status) == false), {}, QUERY_NORMALIZATION_ERROR, ("u_strFromUTF8 FAIL(%s)", u_errorName(status))); + + u_strToLower(tmp_result, dest_size, tmp_result, -1, NULL, &status); + ADVANCED_CATCH_SET_ERROR((U_FAILURE(status) == false), {}, QUERY_NORMALIZATION_ERROR, ("u_strToLower FAIL(%s)", u_errorName(status))); + + ADVANCED_SVC_TRACE("src : %s", src); + + size = unorm_normalize(tmp_result, -1, UNORM_NFD, 0, (UChar *)result, dest_size, &status); + ADVANCED_CATCH_SET_ERROR((U_FAILURE(status) == false), {}, QUERY_NORMALIZATION_ERROR, ("unorm_normalize FAIL(%s)", u_errorName(status))); + + u_strToUTF8(dest, dest_size, &size, result, -1, &status); + ADVANCED_CATCH_SET_ERROR((U_FAILURE(status) == false), {}, QUERY_NORMALIZATION_ERROR, ("u_strToUTF8 FAIL(%s)", u_errorName(status))); + + ADVANCED_SVC_TRACE("dest : %s", (char *)dest); + +CATCH: + g_free(tmp_result); + g_free(result); + + return error_code; +} + +query_error _remove_invalid_chars(char *src, char* desc) +{ + ADVANCED_RETURN_VAL((src != NULL), {}, QUERY_NULL_PARAMETER, ("SOURCE STRING IS NULL")); + ADVANCED_SVC_TRACE("%s", src); + + int i = 0; + int j = 0; + int nSrc = 0; + query_error error_code = QUERY_SUCCESS; + + nSrc = strlen(src); + + for(i = 0; i < nSrc; ++i) + { + switch(src[i]) + { + case '[': + case '\\': + case ']': + case '^': + case '_': + case '`': + case ' ': +/* + case '(': + case ')': + case '-': + case ' ': + case '/': +*/ + break; + default: + desc[j++] = src[i]; + break; + } + } + desc[j] = '\0'; + ADVANCED_SVC_TRACE("%s", desc); + + return error_code; +} + +int _convert_type_string_to_int(contact_attribute_e attribute, const char* value) +{ + int integer_value = 0; + char* loc = 0; + int i = 0; + + switch(attribute) + { + case CONTACT_ID : + case ACCOUNT_ID : + { + integer_value = atoi(value); + } + break; + case CONTACT_LAST_UPDATED_TIME_STAMP : + { + integer_value = atoi(value); + } + break; +// case CONTACT_READ_ONLY : +// case CONTACT_SEND_TO_VOICE_MAIL : + case CONTACT_IS_FAVORITE : + { + if(strcmp(value, "TRUE") == 0) + integer_value = 1; + else if(strcmp(value, "FALSE") == 0) + integer_value = 0; + } + break; + case NUMBER_TYPES: + { + for(i = 1; i <= MAX_NUMBER_TYPE; i++) + { + loc = strstr(value, number_type_str[i]); + if(loc != NULL) + { + switch(i) + { + case 1: + integer_value = (integer_value | HOME); + break; + case 2: + integer_value = (integer_value | WORK); + break; + case 3: + integer_value = (integer_value | VOICE); + break; + case 4: + integer_value = (integer_value | FAX); + break; + case 5: + integer_value = (integer_value | MSG); + break; + case 6: + integer_value = (integer_value | CELL); + break; + case 7: + integer_value = (integer_value | PAGER); + break; + case 8: + integer_value = (integer_value | BBS); + break; + case 9: + integer_value = (integer_value | MODEM); + break; + case 10: + integer_value = (integer_value | CAR); + break; + case 11: + integer_value = (integer_value | ISDN); + break; + case 12: + integer_value = (integer_value | VIDEO); + break; + case 13: + integer_value = (integer_value | PCS); + break; + default: + break; + } + } + } + } + break; + case EMAIL_TYPE: + { + for(i = 1; i <= MAX_EMAIL_TYPE; i++) + { + loc = strstr(value, email_type_str[i]); + if(loc != NULL) + { + switch(i) + { + case 1: + integer_value = (integer_value | EMAIL_HOME); + break; + case 2: + integer_value = (integer_value | EMAIL_WORK); + break; + default: + break; + } + } + } + } + break; + case URL_TYPE: + { + for(i = 1; i < URL_TYPE_MAX; i++) + { + if(strcmp(url_type_str[i], value) == 0) + integer_value = URL_HOME; + else + integer_value = URL_WORK; + } + } + break; + case ADDRESS_TYPE: + { + for(i = 1; i <= MAX_ADDRESS_TYPE; i++) + { + loc = strstr(value, addr_type_str[i]); + if(loc != NULL) + { + switch(i) + { + case 1: + integer_value = (integer_value | ADDRESS_TYPE_HOME); + break; + case 2: + integer_value = (integer_value | ADDRESS_TYPE_WORK); + break; + case 3: + integer_value = (integer_value | ADDRESS_TYPE_DOM); + break; + case 4: + integer_value = (integer_value | ADDRESS_TYPE_INTL); + break; + case 5: + integer_value = (integer_value | ADDRESS_TYPE_POSTAL); + break; + case 6: + integer_value = (integer_value | ADDRESS_TYPE_PARCEL); + break; + default: + break; + } + } + } + } + break; + case EVENT_TYPE: + { + for(i = 0; i < EVENT_TYPE_MAX; i++) + { + if(strcmp(event_type_str[i], value) == 0) + integer_value = EVENT_BIRTHDAY; + else + integer_value = EVENT_ANNIVERSARY; + } + } + break; + default: + break; + } +// ADVANCED_SVC_TRACE("integer_value : %d", integer_value); + + return (int)integer_value; +} + diff --git a/src/platform/Tizen/Contact/query-svc/query-utility.h b/src/platform/Tizen/Contact/query-svc/query-utility.h new file mode 100755 index 0000000..c9848fc --- /dev/null +++ b/src/platform/Tizen/Contact/query-svc/query-utility.h @@ -0,0 +1,451 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @file query-utility.h + * @author JihwaPark (82-32-3016262, jh7979.park@samsung.com) + * @version 1.0(2010.10.05) + * @brief This file is internal header file for own module + */ + +#ifndef __QUERY_UTILITY_H__ +#define __QUERY_UTILITY_H__ + +#include "query-service.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +sqlite3 *g_hDBCt; + +#define QUERY_DB_PATH "/opt/dbspace/.contacts-svc.db" + +typedef enum +{ + INTEGER = 0, + STRING, + REAL +}primitive_type; + +typedef enum +{ + TABLE_INVALID = -1, + TABLE_PERSON, + TABLE_CONTACT, + TABLE_DATA, + TABLE_PRESENCE, + TABLE_GROUP, + TABLE_GROUP_RELATION, + TABLE_MAX, +}table_name_e; + +typedef enum +{ + FIELD_INVALID = -1, + FIELD_PERSON_CONTACT_ID, + FIELD_PERSON_IS_SELF, + FIELD_CONTACT_ID_FOR_NAME, + FIELD_CONTACT_ID_FOR_PHOTO, + FIELD_CONTACT_ID_FOR_RINGTONE, + FIELD_PERSON_PREFIX_NAME, + FIELD_PERSON_FIRST_NAME, + FIELD_PERSON_MIDDLE_NAME, + FIELD_PERSON_LAST_NAME, + FIELD_PERSON_PHONETIC_NAME, + FIELD_PERSON_DISPLAY_NAME = 10, + FIELD_PERSON_PHOTO_URI, + FIELD_PERSON_LAST_UPDATED_TIME, + FIELD_PERSON_IS_FAVORITE, + FIELD_PERSON_SEND_TO_VOICEMAIL, + FIELD_PERSON_RINGTONE, + + FIELD_CONTACT_PERSON_ID, + FIELD_CONTACT_CONTACT_ID, + FIELD_CONTACT_ACCOUNT_ID, + FIELD_CHANGED_TIME, + FIELD_IS_FAVORITE, + FIELD_RINGTONE, + FIELD_NOTE, + FIELD_UID, + + FIELD_DATA_PERSON_ID, + FIELD_DATA_CONTACT_ID, + FIELD_DATA_DATATYPE_ID, + FIELD_DATA1, + FIELD_DATA2, + FIELD_DATA3, + FIELD_DATA4, + FIELD_DATA5, + FIELD_DATA6, + FIELD_DATA7, + FIELD_DATA8, + FIELD_DATA9, + FIELD_DATA10, + FIELD_PRESENCE_CONTACT_ID, + FIELD_PRESENCE_STATE, + FIELD_PRESENCE_MESSAGE, + FIELD_PRESENCE_ICON_URI, + FIELD_PRESENCE_CAPABILITY, + FIELD_MAX +}data_field_e; + +static char* field_key[FIELD_MAX] = +{ + "person.person_id", //0 + "person.is_self", + "person.contact_id_for_name", + "person.contact_id_for_photo", + "person.contactid_for_ringtone", + "person.prefix", + "person.first_name", + "person.middle_name", + "person.last_name", + "person.phonetic_name", + "person.display_name", //10 + "person.photo_URI", + "person.last_updated_timestamp", + "person.is_favorite", + "person.send_to_voicemail", + "person.ringtone", + "contacts.person_id", + "contacts.contact_id", + "contacts.addrbook_id", + "contacts.changed_time", + "contacts.is_favorite", + "contacts.ringtone", + "contacts.note", + "contacts.uid", + "data.person_id", + "data.contact_id", + "data.datatype", + "data.data1", + "data.data2", + "data.data3", + "data.data4", + "data.data5", + "data.data6", + "data.data7", + "data.data8", + "data.data9", + "data.data10", + "presence.contact_id", + "presence.state", + "presence.message", + "presence.icon_uri", + "presence.capability" +}; + +static char* condition_field_key[FIELD_MAX] = +{ + "person_id", //0 + "is_self", + "contact_id_for_name", + "contact_id_for_photo", + "contactid_for_ringtone", + "prefix", + "first_name", + "middle_name", + "last_name", + "phonetic_name", + "display_name", //10 + "photo_URI", + "last_updated_timestamp", + "is_favorite", + "send_to_voicemail", + "ringtone", + "person_id", + "contact_id", + "addrbook_id", + "changed_time", + "is_favorite", + "ringtone", + "note", + "uid", + "person_id", + "contact_id", + "datatype", + "data1", + "data2", + "data3", + "data4", + "data5", + "data6", + "data7", + "data8", + "data9", + "data10", + "contact_id", + "state", + "message", + "icon_uri", + "capability" +}; + +typedef enum +{ + FIELD_GROUP_INVALID = -1, + FIELD_GROUP_ID, + FIELD_GROUP_NAME, + FIELD_GROUP_RINGTONE, + FIELD_GROUP_MAX, +}group_key; + +static char* group_field_key[FIELD_GROUP_MAX] = +{ + "group_id", //0 + "group_name", + "ringtone" +}; + +typedef enum +{ + FIELD_GROUP_RELATION_INVALID = -1, + FIELD_GROUP_RELATION_GROUP_ID, + FIELD_GROUP_RELATION_CONTACT_ID, + FIELD_GROUP_RELATION_MAX, +}group_relation_key; + +static char* relation_field_key[FIELD_GROUP_RELATION_MAX] = +{ + "group_id", //0 + "contact_id" +}; + +typedef enum +{ + FIELD_X_INVALID = -1, + FIELD_X_DATA1, + FIELD_X_DATA2, + FIELD_X_DATA3, + FIELD_X_DATA4, + FIELD_X_DATA5, + FIELD_X_DATA6, + FIELD_X_DATA7, + FIELD_X_DATA8, + FIELD_X_DATA9, + FIELD_X_DATA10, + FIELD_X_MAX, +}x_field_e; + +static char* x_field_key[FIELD_X_MAX] = +{ + "data.data1", //0 + "data.data2", + "data.data3", + "data.data4", + "data.data5", + "data.data6", + "data.data7", + "data.data8", + "data.data9", + "data.data10" +}; + +static char* condition_x_field_key[FIELD_X_MAX] = +{ + "data1", //0 + "data2", + "data3", + "data4", + "data5", + "data6", + "data7", + "data8", + "data9", + "data10" +}; + +static char* alias_key[27] = +{ + " ", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z" +}; + +static char* condition_key[CONDITION_MAX] = +{ + "=", + "!=", + ">", + "<", + ">=", + "<=", + "like" +}; + +static char* table_key[TABLE_MAX] = +{ + "person", + "contacts", + "data", + "presence", + "groups", + "group_relations" +}; + +static char* condition_type_key[CONDITION_TYPE_MAX] = +{ + "(", + ")", + "AND", + "OR" +}; + +clock_t _get_clock(); + +bool _print_time(clock_t begin, clock_t finish, const char* function_name); + +query_error _db_init(); + +query_error _db_finish(); + +query_error _trans_begin(void); + +query_error _trans_end(bool is_success); + +query_error _exec_query(char* query); + +int _query_step(stmt pStmt); + +void _contact_query_finalize(stmt pStmt); + +int _contact_query_column_int(stmt pStmt, int pos); + +char* _contact_query_column_text(stmt pStmt, int pos); + +void _query_finalize(stmt pStmt); + +int _query_bind_int(stmt pStmt, int pos, int num); + +int _query_bind_double(stmt pStmt, int pos, double num); + +int _query_bind_text(stmt pStmt, int pos, char* str); + +void _query_stmt_reset(stmt stmt); + +int _query_column_int(stmt pStmt, int pos); + +double _query_column_double(stmt pStmt, int pos); + +char* _query_column_text(stmt pStmt, int pos); + +stmt _query_prepare(char *query); + +bool _convert_person_attribute_to_mimetype_id(contact_attribute_e attribute); + +predefine_datatype _convert_attribute_to_mimetype_id(contact_attribute_e attribute); + +char* _convert_person_attribute_to_column_name(contact_attribute_e attribute); + +char* _convert_person_attribute_to_condition_column_name(contact_attribute_e attribute); + +char* _convert_attribute_to_condition_normalize_column(contact_attribute_e attribute); + +char* _convert_attribute_to_normalize_column(contact_attribute_e attribute); + +char* _convert_attribute_to_condition_column_name(contact_attribute_e attribute); + +primitive_type _convert_check_attribute_primitive_type(contact_attribute_e attribute); + +char* _convert_x_attribute_to_condition_column_name(contact_x_attribute_e attribute); + +char* _convert_attribute_to_column_name(contact_attribute_e attribute); + +char* _convert_x_attribute_to_column_name(contact_x_attribute_e attribute); + +tables_e _contact_table_name_to_table_type(char* table_name); + +char* _convert_person_attribute_to_table_name(contact_attribute_e attribute); + +char* _convert_attribute_to_table_name(contact_attribute_e attribute); + +char* _convert_x_attribute_to_table_name(contact_x_attribute_e attribute); + +char* _convert_condition_type_to_string(condition_type_e type); + +void _query_get_count(const char* table_name, query_type_e query_type, int* count); + +void __free_datatype_list(gpointer data, gpointer user_data); + +void _free_handle_info(advanced_handle_t* handle); + +int _free_for_limit_iter(advanced_handle_t* handle); + +void _free_name_info(name_t* name_info); + +void _free_num_info(number_t* num_info); + +void _free_email_info(email_t* email_info); + +void _free_url_info(url_t* url_info); + +void _free_nick_info(nick_name_t* nick_info); + +void _free_anniversary_info(event_info_t* event_info); + +void _free_organization_info(organization_t* organization_info); + +void _free_address_info(address_t* address_info); + +void _free_x_info(x_info_t* x_info); + +void _free_projection_list(gpointer data, gpointer user_data); + +db_datatype _convert_datatype_to_db_type(predefine_datatype datatype); + +query_error _set_datatype_list(advanced_handle_t* q_handle, contact_attribute_e attribute); + +query_error _set_datatype_list_by_x_attribute(advanced_handle_t* q_handle, int datatype_id, contact_x_attribute_e attribute); + +char* _convert_condition_to_string(condition_e condition); + +query_error _normalize_str(const char* src, char* dest, int dest_size); + +query_error _remove_invalid_chars(char *src, char* desc); + +int _convert_type_string_to_int(contact_attribute_e attribute, const char* value); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif // __QUERY_UTILITY_H__ + diff --git a/src/platform/Tizen/DBus/Connection.cpp b/src/platform/Tizen/DBus/Connection.cpp new file mode 100755 index 0000000..6f8e9f7 --- /dev/null +++ b/src/platform/Tizen/DBus/Connection.cpp @@ -0,0 +1,348 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "Connection.h" +#include +#include +#include +#include +#include "Message.h" + +namespace TizenApis { +namespace Platform { +namespace DBus { +Connection::Connection() : + m_connection(NULL), + m_messageDispatcher(NULL), + m_connected(false) +{ + dbus_error_init(&m_error); + m_messageDispatcher = new MessageDispatcher(this); +} + +Connection::~Connection() +{ + assert(!m_connected && "DBus connection has not been closed."); + delete m_messageDispatcher; + if (dbus_error_is_set(&m_error)) { + dbus_error_free(&m_error); + } +} + +void Connection::open(DBusBusType bus) +{ + if (m_connected) { return; } + + m_connection = dbus_bus_get(bus, &m_error); + if (!m_connection || dbus_error_is_set(&m_error)) { + std::string message = m_error.message; + dbus_error_free(&m_error); + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, + "Couldn't attach to DBus system bus: " << message); + } + + dbus_connection_set_exit_on_disconnect(m_connection, FALSE); + + for (FilterSetIterator it = m_filters.begin(); it != m_filters.end(); + ++it) { + addFilterInternal(*it); + } + + if (!dbus_connection_set_watch_functions(m_connection, addWatch, + removeWatch, toggleWatch, this, + NULL)) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Couldn't set-up watch functions."); + } + + if (!dbus_connection_add_filter(m_connection, filterMessage, this, NULL)) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Couldn't set signal handler callback."); + } + + m_connected = true; +} + +void Connection::close() +{ + LogDebug("ENTER"); + if (!m_connected) { return; } + + dbus_connection_remove_filter(m_connection, filterMessage, this); + + // Calls removeWatch() automagically. + if (!dbus_connection_set_watch_functions(m_connection, NULL, NULL, NULL, + NULL, NULL)) { + DPL::Mutex::ScopedLock lock(&m_watchesMutex); + WatchSetIterator it = m_watches.begin(); + for (; it != m_watches.end(); ++it) { + if (it->second->isEnabled()) { + m_messageDispatcher->removeDescriptor(it->second->getHandle(), + it->second->getType()); + } + } + m_watches.clear(); + } + + // TODO: think how to handle exception on filter removal; 1 - do nothing (now), + // 2 - remove the buggy one but throw an exception, 3 - remove the buggy one + // and don't throw any exception + for (FilterSetIterator it = m_filters.begin(); it != m_filters.end(); + ++it) { + removeFilterInternal(*it); + } + + dbus_connection_unref(m_connection); + + m_connected = false; +} + +void Connection::addFilter(const std::string& rule) +{ + if (m_connected) { + addFilterInternal(rule); + } + m_filters.insert(rule); +} + +void Connection::removeFilter(const std::string& rule) +{ + if (m_connected) { + removeFilterInternal(rule); + } + m_filters.erase(rule); +} + +void Connection::setWorkerThread(DPL::Thread* thread) +{ + assert(!m_connected && "Connection has already been established."); + m_messageDispatcher->SwitchToThread(thread); +} + +void Connection::addFilterInternal(const std::string& rule) +{ + assert(m_connection && "Connection has to be established first."); + dbus_bus_add_match(m_connection, rule.c_str(), &m_error); + if (dbus_error_is_set(&m_error)) { + std::string message = m_error.message; + dbus_error_free(&m_error); + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "Invalid rule: " << message); + } +} + +void Connection::removeFilterInternal(const std::string& rule) +{ + assert(m_connection && "Connection has to be established first."); + dbus_bus_remove_match(m_connection, rule.c_str(), &m_error); + if (dbus_error_is_set(&m_error)) { + std::string message = m_error.message; + dbus_error_free(&m_error); + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "Invalid rule: " << message); + } +} + +dbus_bool_t Connection::addWatch(DBusWatch* watch, + void* data) +{ + LogDebug("ENTER"); + assert(data && "Connection should be passed as user data."); + Connection* this_ = static_cast(data); + WatchPtr wrapper(new Watch(watch)); + if (wrapper->isEnabled()) { + this_->m_messageDispatcher->addDescriptor(wrapper->getHandle(), + wrapper->getType()); + } + DPL::Mutex::ScopedLock lock(&this_->m_watchesMutex); + this_->m_watches[wrapper->getHandle()] = wrapper; + return TRUE; +} + +void Connection::removeWatch(DBusWatch* watch, + void* data) +{ + LogDebug("ENTER"); + assert(data && "Connection should be passed as user data."); + Connection* this_ = static_cast(data); + Watch wrapper(watch); + if (wrapper.isEnabled()) { + this_->m_messageDispatcher->removeDescriptor(wrapper.getHandle(), + wrapper.getType()); + } + DPL::Mutex::ScopedLock lock(&this_->m_watchesMutex); + this_->m_watches.erase(wrapper.getHandle()); +} + +void Connection::toggleWatch(DBusWatch* watch, + void* data) +{ + LogDebug("ENTER"); + assert(data && "Connection should be passed as user data."); + Connection* this_ = static_cast(data); + Watch wrapper(watch); + if (wrapper.isEnabled()) { + this_->m_messageDispatcher->addDescriptor(wrapper.getHandle(), + wrapper.getType()); + } else { + this_->m_messageDispatcher->removeDescriptor(wrapper.getHandle(), + wrapper.getType()); + } +} + +DBusHandlerResult Connection::filterMessage(DBusConnection* connection, + DBusMessage* message, + void* data) +{ + LogDebug("ENTER"); + if (data) { + Connection* this_ = static_cast(data); + MessagePtr msg; + if (message) { + LogInfo( + "DBUS message received from interface: " << + dbus_message_get_interface(message)); + msg.Reset(new Message(message)); + } else { + LogError("DBus message not set, this should not happen!"); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + + FilterSetIterator it = this_->m_filters.begin(); + for (; it != this_->m_filters.end(); ++it) { + // TODO: extend following matching procedure to check not only + // interface's name. + if ((*it).find(msg->getInterface()) != std::string::npos) { + MessageEvent event(msg); + this_->EmitEvent(event); + } + } + } else { + LogError("User-data not set, this should not happen!"); + } + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; +} + +Connection::MessageDispatcher::MessageDispatcher(Connection* connection) : + m_connection(connection) +{ + assert(m_connection && "Connection cannot be NULL."); + DPL::ControllerEventHandler::Touch(); + DPL::ControllerEventHandler::Touch(); +} + +Connection::MessageDispatcher::~MessageDispatcher() +{ + SwitchToThread(NULL); +} + +void Connection::MessageDispatcher::addDescriptor(DPL::WaitableHandle handle, + DPL::WaitMode::Type mode) +{ + LogDebug("ENTER"); + DPL::WaitableEvent wait; + AddDescriptorSyncEvent event(handle, mode, &wait); + DPL::ControllerEventHandler::PostEvent(event); + DPL::WaitForSingleHandle(wait.GetHandle()); +} + +void Connection::MessageDispatcher::removeDescriptor(DPL::WaitableHandle handle, + DPL::WaitMode::Type mode) +{ + LogDebug("ENTER"); + DPL::WaitableEvent wait; + RemoveDescriptorSyncEvent event(handle, mode, &wait); + DPL::ControllerEventHandler::PostEvent(event); + DPL::WaitForSingleHandle(wait.GetHandle()); +} + +void Connection::MessageDispatcher::OnEventReceived( + const AddDescriptorSyncEvent& event) +{ + LogDebug("ENTER"); + DPL::WaitableHandleWatchSupport::InheritedContext()->AddWaitableHandleWatch( + this, + event.GetArg0(), + event.GetArg1()); + event.GetArg2()->Signal(); +} + +void Connection::MessageDispatcher::OnEventReceived( + const RemoveDescriptorSyncEvent& event) +{ + LogDebug("ENTER"); + DPL::WaitableHandleWatchSupport::InheritedContext()-> + RemoveWaitableHandleWatch(this, event.GetArg0(), event.GetArg1()); + event.GetArg2()->Signal(); +} + +void Connection::MessageDispatcher::OnWaitableHandleEvent( + DPL::WaitableHandle waitableHandle, + DPL::WaitMode::Type mode) +{ + LogDebug("ENTER"); + { + DPL::Mutex::ScopedLock lock(&m_connection->m_watchesMutex); + WatchSetIterator it = m_connection->m_watches.find(waitableHandle); + if (it != m_connection->m_watches.end()) { + unsigned int flags = + (mode == DPL::WaitMode::Write ? DBUS_WATCH_WRITABLE + : DBUS_WATCH_READABLE); + while (!dbus_watch_handle(it->second->get(), flags)) { + LogError("Too few memory!"); + // TODO: add some check-point to not loop infinitely + } + } + // TODO: not sure if there is point in dispatching connection when watch not found? + } + dbus_connection_ref(m_connection->m_connection); + while (dbus_connection_dispatch(m_connection->m_connection) == + DBUS_DISPATCH_DATA_REMAINS) { + } + dbus_connection_unref(m_connection->m_connection); +} + +Connection::Watch::Watch(DBusWatch* watch) : m_watch(watch) +{ + assert(m_watch && "Watch cannot be NULL."); +} + +DPL::WaitableHandle Connection::Watch::getHandle() const +{ + return dbus_watch_get_unix_fd(m_watch); +} + +DPL::WaitMode::Type Connection::Watch::getType() const +{ + if ((dbus_watch_get_flags(m_watch) & DBUS_WATCH_WRITABLE) != 0) { + return DPL::WaitMode::Write; + } + return DPL::WaitMode::Read; +} + +bool Connection::Watch::isEnabled() const +{ + return (TRUE == dbus_watch_get_enabled(m_watch)); +} + +DBusWatch* Connection::Watch::get() const +{ + return m_watch; +} +} // DBus +} // Platform +} // WrtPlugins diff --git a/src/platform/Tizen/DBus/Connection.h b/src/platform/Tizen/DBus/Connection.h new file mode 100755 index 0000000..32883fc --- /dev/null +++ b/src/platform/Tizen/DBus/Connection.h @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTPLUGINS_DBUS_CONNECTION_H_ +#define WRTPLUGINS_DBUS_CONNECTION_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "MessageEvent.h" + +namespace TizenApis { +namespace Platform { +namespace DBus { +class Connection : public DPL::EventSupport +{ + public: + typedef DPL::EventListener EventListener; + + public: + Connection(); + ~Connection(); + + void open(DBusBusType bus); + void close(); + void addFilter(const std::string& rule); + void removeFilter(const std::string& rule); + void setWorkerThread(DPL::Thread* thread); + + private: + DECLARE_GENERIC_EVENT_3(AddDescriptorSyncEvent, + DPL::WaitableHandle, + DPL::WaitMode::Type, + DPL::WaitableEvent*) + + DECLARE_GENERIC_EVENT_3(RemoveDescriptorSyncEvent, + DPL::WaitableHandle, + DPL::WaitMode::Type, + DPL::WaitableEvent*) + + class MessageDispatcher : public DPL::Controller + ::Type >, + private DPL::WaitableHandleWatchSupport::WaitableHandleListener + { + public: + explicit MessageDispatcher(Connection* connection); + ~MessageDispatcher(); + void addDescriptor(DPL::WaitableHandle handle, + DPL::WaitMode::Type mode); + void removeDescriptor(DPL::WaitableHandle handle, + DPL::WaitMode::Type mode); + + protected: + void OnEventReceived(const AddDescriptorSyncEvent& event); + void OnEventReceived(const RemoveDescriptorSyncEvent& event); + void OnWaitableHandleEvent(DPL::WaitableHandle waitableHandle, + DPL::WaitMode::Type mode); + + private: + Connection* m_connection; + }; + + class Watch : private DPL::Noncopyable + { + public: + explicit Watch(DBusWatch* watch); + + inline DPL::WaitableHandle getHandle() const; + inline DPL::WaitMode::Type getType() const; + inline bool isEnabled() const; + inline DBusWatch* get() const; + + private: + DBusWatch* m_watch; + }; + typedef DPL::SharedPtr WatchPtr; + + typedef std::map WatchSet; + typedef WatchSet::iterator WatchSetIterator; + + typedef std::set FilterSet; + typedef FilterSet::iterator FilterSetIterator; + + private: + static dbus_bool_t addWatch(DBusWatch* watch, + void* data); + static void removeWatch(DBusWatch* watch, + void* data); + static void toggleWatch(DBusWatch* watch, + void* data); + static DBusHandlerResult filterMessage(DBusConnection* connection, + DBusMessage* message, + void* data); + + private: + void addFilterInternal(const std::string& rule); + void removeFilterInternal(const std::string& rule); + + private: + DBusConnection* m_connection; + DBusError m_error; + + MessageDispatcher* m_messageDispatcher; + bool m_connected; + FilterSet m_filters; + WatchSet m_watches; + DPL::Mutex m_watchesMutex; +}; + +typedef DPL::SharedPtr ConnectionPtr; +} // DBus +} // Platform +} // WrtPlugins + +#endif // WRTPLUGINS_DBUS_CONNECTION_H_ diff --git a/src/platform/Tizen/DBus/Message.cpp b/src/platform/Tizen/DBus/Message.cpp new file mode 100755 index 0000000..d897c5f --- /dev/null +++ b/src/platform/Tizen/DBus/Message.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "Message.h" +#include +#include + +namespace TizenApis { +namespace Platform { +namespace DBus { +Message::Message(DBusMessage* message) : m_message(message) +{ + assert(m_message && "Message cannot be NULL."); + addRef(); +} + +Message::Message(int type) +{ + m_message = dbus_message_new(type); + if (!m_message) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Out of memory."); + } + addRef(); +} + +Message::~Message() +{ + unref(); +} + +int Message::getType() const +{ + return dbus_message_get_type(m_message); +} + +std::string Message::getInterface() const +{ + const char* interface = dbus_message_get_interface(m_message); + return (interface ? interface : std::string()); +} + +std::string Message::getPath() const +{ + const char* path = dbus_message_get_path(m_message); + return (path ? path : std::string()); +} + +bool Message::isSignal(const std::string& name) const +{ + return (dbus_message_is_signal(m_message, + getInterface().c_str(), + name.c_str()) + == TRUE); +} + +Message::ReadIterator Message::getReadIterator() const +{ + return ReadIterator(new ReadIterator_(m_message)); +} + +void Message::addRef() +{ + m_message = dbus_message_ref(m_message); +} + +void Message::unref() +{ + dbus_message_unref(m_message); +} + +Message::ReadIterator_::ReadIterator_(DBusMessage* message) +{ + assert(message && "Message cannot be NULL."); + m_valid = dbus_message_iter_init(message, &m_iterator); +} + +bool Message::ReadIterator_::next() +{ + if (!m_valid) { + Throw(WrtDeviceApis::Commons::OutOfRangeException); + } + return (m_valid = (dbus_message_iter_next(&m_iterator) == TRUE)); +} + +bool Message::ReadIterator_::isValid() const +{ + return m_valid; +} + +int Message::ReadIterator_::getArgType() const +{ + if (!m_valid) { + Throw(WrtDeviceApis::Commons::OutOfRangeException); + } + return dbus_message_iter_get_arg_type(&m_iterator); +} + +int Message::ReadIterator_::getInt() const +{ + return static_cast(getArgBasic(DBUS_TYPE_INT32)); +} + +std::string Message::ReadIterator_::getString() const +{ + return getArgBasic(DBUS_TYPE_STRING); +} + +template +T Message::ReadIterator_::getArgBasic(int type) const +{ + if (getArgType() != type) { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Type mismatch."); + } + + if (!m_valid) { + Throw(WrtDeviceApis::Commons::OutOfRangeException); + } + + T result; + dbus_message_iter_get_basic(&m_iterator, &result); + return result; +} +} // DBus +} // Platform +} // WrtPlugins diff --git a/src/platform/Tizen/DBus/Message.h b/src/platform/Tizen/DBus/Message.h new file mode 100755 index 0000000..b383d1c --- /dev/null +++ b/src/platform/Tizen/DBus/Message.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTPLUGINS_DBUS_MESSAGE_H_ +#define WRTPLUGINS_DBUS_MESSAGE_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace DBus { +class Message : private DPL::Noncopyable +{ + private: + class ReadIterator_; + + public: + typedef DPL::SharedPtr ReadIterator; + + public: + explicit Message(DBusMessage* message); + explicit Message(int type); + ~Message(); + + int getType() const; + std::string getInterface() const; + std::string getPath() const; + bool isSignal(const std::string& name) const; + ReadIterator getReadIterator() const; + + private: + // It doesn't need to be non-copyable - DBusMessageIter doesn't require it. + class ReadIterator_ + { + public: + explicit ReadIterator_(DBusMessage* message); + + bool next(); + bool isValid() const; + + int getArgType() const; + + int getInt() const; + std::string getString() const; + + private: + template + T getArgBasic(int type) const; + + private: + mutable DBusMessageIter m_iterator; + bool m_valid; + }; + + private: + inline void addRef(); + inline void unref(); + + private: + DBusMessage* m_message; +}; + +typedef DPL::SharedPtr MessagePtr; +} // DBus +} // Platform +} // WrtPlugins + +#endif // WRTPLUGINS_DBUS_MESSAGE_H_ diff --git a/src/platform/Tizen/DBus/MessageEvent.h b/src/platform/Tizen/DBus/MessageEvent.h new file mode 100755 index 0000000..4053882 --- /dev/null +++ b/src/platform/Tizen/DBus/MessageEvent.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTPLUGINS_DBUS_MESSAGEEVENT_H_ +#define WRTPLUGINS_DBUS_MESSAGEEVENT_H_ + +#include +#include "Message.h" + +namespace TizenApis { +namespace Platform { +namespace DBus { +DECLARE_GENERIC_EVENT_1(MessageEvent, MessagePtr) +} // DBus +} // Platform +} // WrtPlugins + +#endif // WRTPLUGINS_DBUS_MESSAGEEVENT_H_ diff --git a/src/platform/Tizen/DBus/config.cmake b/src/platform/Tizen/DBus/config.cmake new file mode 100644 index 0000000..1cf8150 --- /dev/null +++ b/src/platform/Tizen/DBus/config.cmake @@ -0,0 +1,16 @@ +get_current_path() + +pkg_search_module(dbus REQUIRED dbus-1) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_DBUS + ${dbus_INCLUDE_DIRS} +) + +set(LIBS_PLATFORM_IMPLEMENTATION_DBUS + ${dbus_LIBRARIES} +) + +set(SRCS_PLATFORM_IMPLEMENTATION_DBUS + ${CURRENT_PATH}/Connection.cpp + ${CURRENT_PATH}/Message.cpp +) diff --git a/src/platform/Tizen/Geocoder/Geocoder.cpp b/src/platform/Tizen/Geocoder/Geocoder.cpp new file mode 100644 index 0000000..d7d0434 --- /dev/null +++ b/src/platform/Tizen/Geocoder/Geocoder.cpp @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* + * @author Sangtai.kim (sangtai.kim@samsung.com) + */ + +#include "Geocoder.h" +#include +#include +#include + +using namespace TizenApis::Tizen1_0::Api::Geocoder; +using namespace DPL; + +namespace TizenApis { +namespace Tizen1_0{ +namespace Platform { +namespace Geocoder { + +namespace{ + bool geocoder_get_position_cb(double latitude, double longitude, void* eventPtr){ + LogDebug("<<< latitude:" << latitude << ", " << longitude); + + if(eventPtr != NULL){ + Api::Geocoder::EventGeocoder* event = (Api::Geocoder::EventGeocoder*)eventPtr; + event->setLatitude(latitude); + event->setLongitude(longitude); + } + + LogDebug(">>>"); + return true; + } +} + +Geocoder::Geocoder() : + m_initialized(false), m_geocoder_handle(NULL) { + LogDebug("Enter"); +} + +Geocoder::~Geocoder() { + LogDebug("<<<"); + + int retVal = GEOCODER_ERROR_NONE; + if(m_geocoder_handle != NULL){ + retVal = geocoder_destroy(m_geocoder_handle); + } + + if (retVal != GEOCODER_ERROR_NONE){ + LogError("Geocoder destruction failed"); + }else{ + LogDebug("Geocoder destroyed"); + } + + LogDebug(">>>"); +} + +void Geocoder::getAddressFromPosition(const Api::Geocoder::EventGeocoderPtr& event) { + LogDebug("<<<"); + + LogDebug("event->getLatitude():" << event->getLatitude()); + LogDebug("event->getLongitude():" << event->getLongitude()); + + if (m_initialized == false) { + initialize(); + } + + EventRequestReceiver::PostRequest(event); + + LogDebug(">>>"); +} + +void Geocoder::printEventData(const Api::Geocoder::EventGeocoderPtr& event) { + LogDebug("country:" << event->getCountry()); + LogDebug("region:" << event->getRegion()); + LogDebug("county:" << event->getCounty()); + LogDebug("city:" << event->getCity()); + LogDebug("street:" << event->getStreet()); + LogDebug("streetNumber:" << event->getStreetNumber()); + LogDebug("premises:" << event->getPremises()); + LogDebug("additionalInformation:" << event->getAdditionalInformation()); + LogDebug("postalCode:" << event->getPostalCode()); +} + +void Geocoder::getPositionFromAddress(const Api::Geocoder::EventGeocoderPtr& event) { + LogDebug("<<<"); + + printEventData(event); + + if (m_initialized == false) { + initialize(); + } + + EventRequestReceiver::PostRequest(event); + + LogDebug(">>>"); +} + +void Geocoder::checkAndSetErrorCodeToEvent(int geocoderRetValue, const Api::Geocoder::EventGeocoderPtr& event) { + switch (geocoderRetValue) { + case GEOCODER_ERROR_INVALID_PARAMETER: + LogDebug("GEOCODER_ERROR_INVALID_PARAMETER"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::InvalidArgumentException); + break; + case GEOCODER_ERROR_NETWORK_FAILED: + LogDebug("GEOCODER_ERROR_NETWORK_FAILED"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::PlatformException); + break; + case GEOCODER_ERROR_SERVICE_NOT_AVAILABLE: + LogDebug("GEOCODER_ERROR_SERVICE_NOT_AVAILABLE"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::PlatformWrongStateException); + break; + default: + LogDebug("UNKNOWN ERROR"); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + } + return; +} + +void Geocoder::getPositionFromPlatform(const Api::Geocoder::EventGeocoderPtr& event) { + LogInfo("<<<"); + printEventData(event); + + double latitude = 0; + double longitude = 0; + + int result = GEOCODER_ERROR_NONE; + + std::string strAddress = event->getAddressString(); + LogDebug("c_str Address:[" << strAddress.c_str() << "]"); + + result = geocoder_foreach_positions_from_address_sync(m_geocoder_handle, strAddress.c_str(), geocoder_get_position_cb, event.Get() ); + LogDebug("after geocoder_foreach_positions_from_address_sync" ); + + latitude = 10.12; + longitude = -12.12; + + if (result != GEOCODER_ERROR_NONE) { + checkAndSetErrorCodeToEvent(result, event); + } + + printEventData(event); + + LogInfo(">>>"); +} + +void Geocoder::getAddressFromPlatform(const Api::Geocoder::EventGeocoderPtr& event) +{ + LogDebug("<<<"); + + char *country_code = NULL; + char *state = NULL; + char *district = NULL; + char *city = NULL; + char *street = NULL; + char *postal_code = NULL; + char *building_number = NULL; + + double latitude = event->getLatitude(); + double longitude = event->getLongitude(); + + printf("[%s][%d] latitude:%f, longitude:%f\n", __FILE__, __LINE__, latitude, longitude); + LogDebug("latitude:" << latitude << ", longitude:" << longitude); + + int result = geocoder_get_address_from_position_sync(m_geocoder_handle, + latitude, longitude, + &building_number, + &postal_code, + &street, + &city, + &district, + &state, + &country_code); + + if(result != GEOCODER_ERROR_NONE){ + checkAndSetErrorCodeToEvent(result, event); + return; + } + + LogDebug("after geocoder_get_address_from_position_sync result:" << result); + LogDebug("country_code111:[" << country_code << "]"); + LogDebug("state:[" << state << "]"); + LogDebug("district:[" << district << "]"); + LogDebug("city:[" << city << "]"); + LogDebug("street:[" << street << "]"); + LogDebug("postal_code:[" << postal_code << "]"); + LogDebug("building_number:[" << building_number << "]"); + + if (country_code != NULL) { + event->setCountry(country_code); + } + + if (state != NULL) { + event->setRegion(state); + } + + if (district != NULL) { + event->setCounty(district); + } + + if (city != NULL) { + event->setCity(city); + } + + if (street != NULL) { + event->setStreet(street); + } + + if (postal_code != NULL) { + event->setPostalCode(postal_code); + } + + if (building_number != NULL) { + event->setPremises(building_number); + } + + free(country_code); + free(state); + free(district); + free(city); + free(street); + free(postal_code); + free(building_number); + + LogDebug(">>>"); +} + +void Geocoder::OnRequestReceived(const Api::Geocoder::EventGeocoderPtr& event) +{ + LogDebug("<<<"); + + if(event->getEventType() == EventGeocoder::GEOCODER_EVENT_GET_POSITION){ + getPositionFromPlatform(event); + }else if(event->getEventType() == EventGeocoder::GEOCODER_EVENT_GET_ADDRESS){ + getAddressFromPlatform(event); + }else{ + LogError("[ERROR] UNKNOWN EVENT TYPE"); + //return error; + } + + LogDebug(">>>"); +} + +void Geocoder::initialize() { + LogDebug("<<<"); + + int retVal = GEOCODER_ERROR_NONE; + + if (!m_initialized) { + DPL::Mutex::ScopedLock lock(&m_initializationMutex); + if (!m_initialized) { + retVal = geocoder_create(&m_geocoder_handle); + if(retVal != GEOCODER_ERROR_NONE){ + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Couldn't init geocoder module."); + } + + m_initialized = true; + } + } + + LogDebug(">>>"); +} + +} //namespace Geocoder +} //namespace Platform +} +} //namespace TizenApis diff --git a/src/platform/Tizen/Geocoder/Geocoder.h b/src/platform/Tizen/Geocoder/Geocoder.h new file mode 100644 index 0000000..197a746 --- /dev/null +++ b/src/platform/Tizen/Geocoder/Geocoder.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* + * @author + * @version 0.1 + * @brief + */ + +#ifndef WRTPLUGINS_PLATFORM_GEOLOCATION_H_ +#define WRTPLUGINS_PLATFORM_GEOLOCATION_H_ + +#include +#include +#include +#include +#include +#include + +#include + +#include + + + +namespace TizenApis { +namespace Tizen1_0 { +namespace Platform { +namespace Geocoder { + +class Geocoder: public Api::Geocoder::IGeocoder { + + friend class Api::Geocoder::GeocoderFactory; + +public: + virtual ~Geocoder(); + + virtual void getAddressFromPosition(const Api::Geocoder::EventGeocoderPtr& event); + virtual void getPositionFromAddress(const Api::Geocoder::EventGeocoderPtr& event); + +protected: + Geocoder(); + virtual void OnRequestReceived(const Api::Geocoder::EventGeocoderPtr& event); + +private: + void getAddressFromPlatform(const Api::Geocoder::EventGeocoderPtr& event); + void getPositionFromPlatform(const Api::Geocoder::EventGeocoderPtr& event); + + void printEventData(const Api::Geocoder::EventGeocoderPtr& event); + void checkAndSetErrorCodeToEvent(int geocoderRetValue, const Api::Geocoder::EventGeocoderPtr& event); + + void initialize(); + + DPL::Mutex m_initializationMutex; + bool m_initialized; + + geocoder_h m_geocoder_handle; +}; + +} +} +} +} + +#endif /* WRTPLUGINS_PLATFORM_GEOLOCATION_H_ */ diff --git a/src/platform/Tizen/Geocoder/config.cmake b/src/platform/Tizen/Geocoder/config.cmake new file mode 100644 index 0000000..cba89d7 --- /dev/null +++ b/src/platform/Tizen/Geocoder/config.cmake @@ -0,0 +1,21 @@ +get_current_path() + +pkg_search_module(capi-location-geocoder REQUIRED capi-location-geocoder) +#pkg_search_module(glib REQUIRED glib-2.0) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_GEOCODER + ${capi-location-geocoder_INCLUDE_DIRS} + ${glib_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_GEOCODER + ${capi-location-geocoder_LIBRARIES} + ${glib_LIBRARIES} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_GEOCODER + ${CURRENT_PATH}/Geocoder.cpp + PARENT_SCOPE +) diff --git a/src/platform/Tizen/Messaging/Attachment.cpp b/src/platform/Tizen/Messaging/Attachment.cpp new file mode 100755 index 0000000..b1cdd99 --- /dev/null +++ b/src/platform/Tizen/Messaging/Attachment.cpp @@ -0,0 +1,108 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * @file Attachment.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include +#include +#include +#include "Attachment.h" + +#include +#include +#include + +extern "C" { +#include +#include +} + +using namespace WrtDeviceApis::Commons; +using namespace std; + +//-------------------------------------------------------------------------- +namespace TizenApis { +namespace Platform { +namespace Messaging { + +Attachment::Attachment(const string& fullPath, + bool isVirtualPath) +{ + LogDebug("entered"); + init(fullPath, isVirtualPath); +} + +Attachment::Attachment(emf_attachment_info_t* att) +{ + LogDebug("entered"); + + m_attachShortName = std::string(att->name); //set shot Name + m_isDownloaded = att->downloaded; + m_attachmentID = att->attachment_id; + + LogDebug(" showname = " << m_attachShortName << " isDownloaded = " << m_isDownloaded << " attachmentID = " << m_attachmentID); + LogDebug("save name is = " << att->savename); + if ( att->savename ) + { + init( att->savename, false); + } +} + +/* +Attachment::Attachment(const std::string& fullPath, bool isVirtualPath, + const Api::Filesystem::INode& inode): + Api::Filesystem::INode(inode) +{ + LogDebug("entered , inode"); + init(fullPath, isVirtualPath); +} +*/ + +#if 0 +Attachment::Attachment(const std::string& fullPath, bool isVirtualPath, const Api::Filesystem::INode& inode): + IAttachment(inode) +{ + LogDebug("entered , inode"); + init(fullPath, isVirtualPath); +} +#endif + +std::string Attachment::getRealPath(const std::string &path) const +{ + + Try + { + Api::Filesystem::IPathPtr currentPath = Api::Filesystem::IPath::create( + path); + return currentPath->getFullPath(); + } + + Catch(WrtDeviceApis::Commons::Exception) { + LogError("invalid path"); + ReThrow(WrtDeviceApis::Commons::InvalidArgumentException); + } + +} +} +} +} + diff --git a/src/platform/Tizen/Messaging/Attachment.h b/src/platform/Tizen/Messaging/Attachment.h new file mode 100755 index 0000000..1a2f99c --- /dev/null +++ b/src/platform/Tizen/Messaging/Attachment.h @@ -0,0 +1,57 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * @file Attachment.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef MESSAGE_ATTACHMENT_H +#define MESSAGE_ATTACHMENT_H + +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { +//-------------------------------------------------------------------------- + +class Attachment : public Api::Messaging::IAttachment +{ + public: + + explicit Attachment(const std::string& fullPath, bool isVirtualPath); + explicit Attachment(emf_attachment_info_t* att); + + // explicit Attachment( const TizenApis::Api::Filesystem::IPathPtr&, TizenApis::Api::Filesystem::NodeType); +#if 0 + explicit Attachment(const std::string& fullPath, bool isVirtualPath, + const Api::Filesystem::INode& inode); +#endif + private: + + virtual std::string getRealPath(const std::string &path) const; +}; + +} +} +} +#endif diff --git a/src/platform/Tizen/Messaging/BinarySms.cpp b/src/platform/Tizen/Messaging/BinarySms.cpp new file mode 100755 index 0000000..9339e10 --- /dev/null +++ b/src/platform/Tizen/Messaging/BinarySms.cpp @@ -0,0 +1,102 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file BinarySms.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "BinarySms.h" +#include + +using namespace std; +using namespace TizenApis::Api::Messaging; + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +BinarySms::BinarySms(const string& id) : + IMessage(BINARYSMS, id) +{ + LogDebug("enter"); + + LogDebug("m_id=" << getIdRef()); + LogDebug("m_msgType=" << getMessageType()); +} + +BinarySms::~BinarySms() +{ + LogDebug("enter"); +} + +void BinarySms::update(bool /*draftsOnly*/) +{ + LogDebug("updating m_id=" << getIdRef()); +} + +void BinarySms::readAllData() +{ + //#warning "TODO" +} + +void BinarySms::moveToFolder(const FolderType newFolder) +{ + //#warning "TODO" +} + +void BinarySms::moveToFolder(const string& newFolder) +{ + //#warning "TODO" +} + +void BinarySms::copyToFolder(const FolderType newFolder) +{ + //#warning "TODO" +} + +void BinarySms::copyToFolder(const string& newFolder) +{ + //#warning "TODO" +} + +void BinarySms::remove() +{ + //#warning "TODO" +} + +void BinarySms::updateIsRead() +{ + //#warning "TODO" +} + +int BinarySms::send() +{ + //#warning "TODO" + return -1; +} + +void BinarySms::sendCancel(int handle) +{ + //#warning "TODO" +} +} +} +} diff --git a/src/platform/Tizen/Messaging/BinarySms.h b/src/platform/Tizen/Messaging/BinarySms.h new file mode 100755 index 0000000..e5d0efc --- /dev/null +++ b/src/platform/Tizen/Messaging/BinarySms.h @@ -0,0 +1,69 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file BinarySms.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef BINARY_SMS_H +#define BINARY_SMS_H + +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +class BinarySms : + public Api::Messaging::IBinarySms +{ + public: + + explicit BinarySms(const std::string& id = ""); + + virtual ~BinarySms(); + + // implementation of interface of IMessage class + virtual void update(bool draftsOnly = false); + + virtual void readAllData(); + + virtual void moveToFolder(const Api::Messaging::FolderType newFolder); + + virtual void moveToFolder(const std::string& newFolder); + + virtual void copyToFolder(const Api::Messaging::FolderType newFolder); + + virtual void copyToFolder(const std::string& newFolder); + + virtual void remove(); + + virtual void updateIsRead(); + + virtual int send(); + + virtual void sendCancel(int handle); +}; +} +} +} +#endif diff --git a/src/platform/Tizen/Messaging/CallbackMgr.cpp b/src/platform/Tizen/Messaging/CallbackMgr.cpp new file mode 100755 index 0000000..fabe932 --- /dev/null +++ b/src/platform/Tizen/Messaging/CallbackMgr.cpp @@ -0,0 +1,139 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file CallbackMgr.cpp + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 0.1 + * @brief + */ + +#include "CallbackMgr.h" +#include +#include "ISendingObserver.h" +#include "MsgServiceHandleMgr.h" + +extern "C" { +#include +#include +#include +} + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +CallbackMgr::CallbackMgr() +{ + LogInfo("enter"); + // register callback once per process + if (NULL == MsgGetCommonHandle()) { + LogError("Unable to open handle"); + } else { + if (msg_reg_sent_status_callback(MsgGetCommonHandle(), sendCallback, + static_cast(this)) != + MSG_SUCCESS) { + LogError("callback registration error"); + } else { + LogDebug("callback registred succesfully"); + } + } +} + +CallbackMgr::~CallbackMgr() +{ + LogInfo("enter"); +} + +MSG_ERROR_T CallbackMgr::registerAndSend(SendingFunction sendingFn, + const msg_message_t& message, + ISendingObserver* observer) +{ + LogDebug("trying to send message, msgId=" << msg_get_message_id(message)); + + MSG_SENDINGOPT_S pSendOpt = { false, false, false }; + MSG_REQUEST_S req = {}; + req.reqId = 0; + req.msg = message; + req.sendOpt = pSendOpt; + + DPL::Mutex::ScopedLock lock(&m_mutex); + MSG_ERROR_T err = (*sendingFn)(MsgGetCommonHandle(), &req); + + LogDebug("req.reqId is : " << req.reqId); + + if (err == MSG_SUCCESS) { + if (observer) { + m_sendRequests[req.reqId] = observer; + observer->setSendigRequestId(req.reqId); + observer->setRecipient(msg_get_ith_address(message, 0)); + } + } + return err; +} + +void CallbackMgr::unregister(int reqId) +{ + LogDebug(" reqId is : " << reqId); + DPL::Mutex::ScopedLock lock(&m_mutex); + + SendReqMap::iterator it = m_sendRequests.find(reqId); + if (it == m_sendRequests.end()) { + LogWarning("No matching request found"); + return; + } + LogInfo("Matching send request found!"); + m_sendRequests.erase(it); +} + +void CallbackMgr::sendCallback(MSG_HANDLE_T handle, + MSG_SENT_STATUS_S *sent_status, + void *user_param) +{ + LogInfo( + "callback received. Req id = " << sent_status->reqId << + " Status = " << (int)sent_status->status); + CallbackMgr* instance = static_cast(user_param); + if (!instance) { + LogError("Empty user data!"); + return; + } + + instance->call(sent_status); +} + +void CallbackMgr::call(MSG_SENT_STATUS_S *sent_status) +{ + DPL::Mutex::ScopedLock lock(&m_mutex); + + SendReqMap::iterator it = m_sendRequests.find(sent_status->reqId); + if (it == m_sendRequests.end()) { + LogWarning("No matching request found"); + return; + } + LogInfo("Matching send request found!"); + + // call it + it->second->sendingCallback(sent_status); + + m_sendRequests.erase(it); +} +} +} +} diff --git a/src/platform/Tizen/Messaging/CallbackMgr.h b/src/platform/Tizen/Messaging/CallbackMgr.h new file mode 100755 index 0000000..ad4308d --- /dev/null +++ b/src/platform/Tizen/Messaging/CallbackMgr.h @@ -0,0 +1,83 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file CallbackMgr.h + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef CALLBACKMGR_H_ +#define CALLBACKMGR_H_ + +#include +#include +#include + +extern "C" { +#include +#include +} + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +class ISendingObserver; + +/* + * + */ +class CallbackMgr +{ + protected: + CallbackMgr(); + + static void sendCallback(MSG_HANDLE_T handle, + MSG_SENT_STATUS_S *sent_status, + void *user_param); + + void call(MSG_SENT_STATUS_S *sent_status); + + public: + ~CallbackMgr(); + + typedef int (*SendingFunction)(MSG_HANDLE_T, MSG_REQUEST_S*); + + // register for sending callback + MSG_ERROR_T registerAndSend(SendingFunction sendingFn, + const msg_message_t& message, + ISendingObserver* observer); + + // unregister callback + void unregister(int reqId); + + private: + DPL::Mutex m_mutex; + + typedef std::map SendReqMap; + SendReqMap m_sendRequests; +}; + +typedef DPL::Singleton CallbackMgrSingleton; +} +} +} +#endif /* CALLBACKMGR_H_ */ diff --git a/src/platform/Tizen/Messaging/Conversation.cpp b/src/platform/Tizen/Messaging/Conversation.cpp new file mode 100755 index 0000000..a3b55df --- /dev/null +++ b/src/platform/Tizen/Messaging/Conversation.cpp @@ -0,0 +1,558 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** +* @file Conversation.cpp +* @author Kangsoo Lee (wpeter.lee@samsung.com) +* @version 0.1 +*/ + + +#include "Conversation.h" +#include +#include +#include "MsgServiceHandleMgr.h" +#include +#include +#include + +extern "C" { +#include +#include +#include +#include +#include +} + +using namespace DPL; + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +Conversation::Conversation() +{ + +} + +Conversation::Conversation(unsigned int threadId, Api::Messaging::MessageType msgType) +{ + LogDebug("Enter"); + + if (msgType == Api::Messaging::EMAIL) + { + makeConversationFromEmailThreadId(threadId); + } + else + { + makeConversationFromMsgId(threadId, msgType); + } +} + +Conversation::Conversation(std::string threadId, Api::Messaging::MessageType msgType) +{ + LogDebug("Enter"); + + std::istringstream stream(threadId); + + LogDebug("threadId : " << threadId); + + unsigned int number = 0; + stream >> number; + makeConversationFromMsgId(number, msgType); +} + +Conversation::Conversation(unsigned int threadIndex) +{ + makeConversationFromThreadIndex(threadIndex); +} + +void Conversation::makeConversationFromThreadIndex(unsigned int threadIndex) +{ + LogDebug("Enter"); + MSG_HANDLE_T handle = MsgGetCommonHandle(); + MSG_LIST_S convViewList = {0, NULL}; + MSG_THREAD_VIEW_LIST_S threadViewList = {0, NULL}; + MSG_ERROR_T err = MSG_SUCCESS; + unsigned int lastMsgIndex = 0; + char *tempString = NULL; + int addressCount = 0; + int index = 0; + + m_result = true; + + try + { + if (msg_get_thread_view_list(handle, NULL, &threadViewList) != MSG_SUCCESS) + { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, "get thread view fail" ); + } + + if (threadViewList.nCount < 0 || threadIndex >= (unsigned int)threadViewList.nCount) + { + LogDebug(threadIndex << ":" << threadViewList.nCount); + ThrowMsg(WrtDeviceApis::Commons::UnknownException, "invalid index reference" ); + } + + + if (msg_thread_view_get_thread_id(threadViewList.msgThreadInfo[threadIndex]) >= 0) + { + m_Id = msg_thread_view_get_thread_id(threadViewList.msgThreadInfo[threadIndex]); + } + + switch(msg_thread_view_get_message_type(threadViewList.msgThreadInfo[threadIndex])) + { + case MSG_TYPE_SMS: + case MSG_TYPE_SMS_CB: + case MSG_TYPE_SMS_JAVACB: + case MSG_TYPE_SMS_WAPPUSH: + case MSG_TYPE_SMS_MWI: + case MSG_TYPE_SMS_SYNCML: + case MSG_TYPE_SMS_REJECT: + m_type = Api::Messaging::SMS; + LogDebug("Type:SMS"); + break; + case MSG_TYPE_MMS: + case MSG_TYPE_MMS_JAVA: + case MSG_TYPE_MMS_NOTI: + m_type = Api::Messaging::MMS;; + LogDebug("Type:MMS"); + break; +// default: + // Todo email / chat + } + + m_time = *(msg_thread_view_get_time(threadViewList.msgThreadInfo[threadIndex])); + m_unreadMessages = msg_thread_view_get_unread_cnt(threadViewList.msgThreadInfo[threadIndex]); + tempString = (char*)msg_thread_view_get_data(threadViewList.msgThreadInfo[threadIndex]); + + if (tempString != NULL) + { + m_preview = tempString; + LogDebug("preview" << m_preview); + } + + + err = msg_get_conversation_view_list(handle, m_Id, &convViewList); + + if (err != MSG_SUCCESS) + { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, "get conversation(msg) view list fail"); + } + + lastMsgIndex = convViewList.nCount - 1; + m_messageCount = convViewList.nCount; + m_read = msg_is_read(convViewList.msgInfo[lastMsgIndex]); + + LogDebug("lastMsgIndex:" << lastMsgIndex << ",message count:" << m_messageCount << ",read" << m_read); + + if (msg_get_direction_info(convViewList.msgInfo[lastMsgIndex]) == MSG_DIRECTION_TYPE_MT) + { + tempString = (char*)msg_get_ith_address(convViewList.msgInfo[lastMsgIndex], 0); + + if (tempString != NULL) + { + m_from = tempString; + } + } + + LogDebug("from" << m_from); + + + tempString = (char*)msg_get_subject(convViewList.msgInfo[lastMsgIndex]); + + if (tempString != NULL) + { + m_subject = tempString; + } + + LogDebug("subject" << m_subject); + + + addressCount = msg_get_address_count(convViewList.msgInfo[lastMsgIndex]); + + + if (addressCount > 0 && addressCount < MAX_TO_ADDRESS_CNT ) + { + for (index = 0; index < addressCount; index++) + { + tempString = (char*)msg_get_ith_address(convViewList.msgInfo[lastMsgIndex], index); + + if (tempString != NULL) + { + m_to.push_back(tempString); + } + } + LogDebug("address count" << addressCount); + } + else + { + LogDebug("address fetch fail" << addressCount); + } + + if (msg_get_message_id(convViewList.msgInfo[lastMsgIndex]) >= 0 ) + { + m_lastMessageId = msg_get_message_id(convViewList.msgInfo[lastMsgIndex]); + } + + LogDebug("message id" << m_lastMessageId); + + } + catch (const WrtDeviceApis::Commons::Exception& ex) + { + m_result = false; + LogError("Exception: " << ex.GetMessage()); + } + if (convViewList.msgInfo != NULL) + { + msg_release_message_list(&convViewList); + } + + if (threadViewList.msgThreadInfo != NULL) + { + msg_release_thread_view_list(&threadViewList); + } + + +} + +bool Conversation::makeConversationFromMsgId(unsigned int threadId, Api::Messaging::MessageType msgType) +{ + LogDebug("Enter"); + MSG_HANDLE_T handle = MsgGetCommonHandle(); + MSG_THREAD_VIEW_LIST_S threadViewList = {0, NULL}; + int conversationId = 0; + int index = 0; + m_result = false; + + if (msg_get_thread_view_list(handle, NULL, &threadViewList) != MSG_SUCCESS) + { + LogDebug("get thread view fail"); + + return m_result; + } + + conversationId = Api::Messaging::IMessaging::getInstance().getConversationId(threadId, msgType); + + for(index = 0; index < threadViewList.nCount; index++) + { + if (conversationId == msg_thread_view_get_thread_id(threadViewList.msgThreadInfo[index])) + { + LogDebug("Found" << conversationId); + makeConversationFromThreadIndex(index); + break; + } + } + + + return m_result; +} + +bool Conversation::makeConversationFromEmailThreadId(unsigned int emailTreadId) +{ + LogDebug("Enter"); + + emf_mail_list_item_t *resultMail = NULL; + emf_mail_list_item_t *mailList = NULL; + int accountId = 0; + int index = 0; + int count = 0; + emf_mailbox_t mailbox = {}; + emf_mail_t *mail = NULL; + + + m_result = true; + + try + { + // Todo : will be re-implemented as using email_get_thread_information_ex + if(email_get_thread_information_ex(emailTreadId, &resultMail) != EMF_ERROR_NONE) + { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, "get email thread fail" ); + } + + + if (email_get_mail(&mailbox, resultMail->mail_id, &mail) != EMF_ERROR_NONE) + { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, "get email data fail" ); + } + + + // account Id + m_unreadMessages = 0; + + if (email_get_mail_list_ex(accountId, NULL, emailTreadId, 0, resultMail->thread_item_count, + EMF_SORT_DATETIME_HIGH, &mailList, &count) != EMF_ERROR_NONE) + { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, "get email data fail" ); + } + + // unread msg count + accountId = resultMail->account_id; + + for (index = 0; index < count; index++) + { + if (mailList[index].flags_seen_field) + { + m_unreadMessages++; + } + LogDebug(mailList[index].flags_seen_field); + } + + // message count + m_messageCount = resultMail->thread_item_count; + // id + m_Id = emailTreadId; + // type + m_type = Api::Messaging::EMAIL; + + // time horrible split + // 2011 11 08 00 35 45 + if (resultMail->datetime[0] != '\0') + { + char buf[MAX_DATETIME_STRING_LENGTH]; + char *targetBuf = resultMail->datetime; + struct tm timeinfo; + + memset(buf, 0x00, sizeof(buf)); + targetBuf += snprintf(buf, sizeof(buf), "%.4s", targetBuf); + timeinfo.tm_year = atoi(buf) - 1900; + + memset(buf, 0x00, sizeof(buf)); + targetBuf += snprintf(buf, sizeof(buf), "%.2s", targetBuf); + timeinfo.tm_mon = atoi(buf) - 1; + + memset(buf, 0x00, sizeof(buf)); + targetBuf += snprintf(buf, sizeof(buf), "%.2s", targetBuf); + timeinfo.tm_mday = atoi(buf); + + + memset(buf, 0x00, sizeof(buf)); + targetBuf += snprintf(buf, sizeof(buf), "%.2s", targetBuf); + timeinfo.tm_hour = atoi(buf); + + memset(buf, 0x00, sizeof(buf)); + targetBuf += snprintf(buf, sizeof(buf), "%.2s", targetBuf); + timeinfo.tm_min = atoi(buf); + + + memset(buf, 0x00, sizeof(buf)); + targetBuf += snprintf(buf, sizeof(buf), "%.2s", targetBuf); + timeinfo.tm_sec = atoi(buf); + + m_time = mktime(&timeinfo); + } + + // preview + // not support +#if 0 + if (resultMail->previewBodyText[0] != '\0') + { + m_preview = resultMail->previewBodyText; + LogDebug(m_preview); + + } + if (mail->head->previewBodyText != NULL) + { + LogDebug(mail->head->previewBodyText); + m_preview = mail->head->previewBodyText; + } +#endif + // read + m_read = (bool)resultMail->flags_seen_field; + + + // from + if (resultMail->from[0] != '\0') + { + m_from = resultMail->from; + LogDebug(m_from); + } + + // subject + if (resultMail->subject[0] != '\0'); + { + m_subject = resultMail->subject; + LogDebug(m_subject); + } + + // to, cc, bcc + if (mail->head!= NULL) + { + if (mail->head->bcc != NULL) + { + LogDebug(mail->head->bcc); + m_bcc.push_back(mail->head->bcc); + } + + if (mail->head->to != NULL) + { + LogDebug(mail->head->to); + m_to.push_back(mail->head->to); + } + + if (mail->head->cc != NULL) + { + LogDebug(mail->head->cc); + m_cc.push_back(mail->head->cc); + } + + } + + m_lastMessageId = resultMail->mail_id; + LogDebug(m_lastMessageId); + m_result = true; + } + catch (const WrtDeviceApis::Commons::Exception& ex) + { + m_result = false; + LogError("Exception: " << ex.GetMessage()); + } + + if (resultMail != NULL) + { + free(resultMail); + } + + if (mail != NULL) + { + email_free_mail(&mail , 1); + } + + return m_result; + +} +Conversation::~Conversation() +{ +} + +#if 0 +// setter +void Conversation::setId(unsigned int id) +{ + m_id = id; +} +void Conversation::setType(unsigned short type) +{ + m_type = type; +} +void Conversation::setTime(time_t time) +{ + m_time = time; +} +void Conversation::setMessageCount(unsigned long messageCount) +{ + m_messageCount = messageCount; +} +void Conversation::setUnreadMessages(unsigned long unreadMessages) +{ + m_unreadMessages = unreadMessages; +} +void Conversation::setPreview(unsigned long preview) +{ + m_preview = preview; +} +void Conversation::setRead(bool read) +{ + m_read = read; +} +void Conversation::setFrom(std::string from) +{ + m_from = from; +} +void Conversation::setTo(std::vector to) +{ + m_to = to; +} +void Conversation::setCC(std::vector cc) +{ + m_cc = cc; +} +void Conversation::setBCC(std::vector bcc) +{ + m_bcc = bcc; +} +void Conversation::setLastMessageId(unsigned int id) +{ + m_lastMessageId = id; +} +#endif +// getter +unsigned int Conversation::getId() +{ + return m_Id; +} +unsigned short Conversation::getType() +{ + return m_type; +} +time_t Conversation::getTime() +{ + return m_time; +} +unsigned long Conversation::getMessageCount() +{ + return m_messageCount; +} +unsigned long Conversation::getUnreadMessages() +{ + return m_unreadMessages; +} +std::string Conversation::getPreview() +{ + return m_preview; +} + +std::string Conversation::getSubject() +{ + return m_subject; +} + + +bool Conversation::getRead() +{ + return m_read; +} +std::string Conversation::getFrom() +{ + return m_from; +} +std::vector Conversation::getTo() +{ + return m_to; +} +std::vector Conversation::getCC() +{ + return m_cc; +} +std::vector Conversation::getBCC() +{ + return m_bcc; +} +unsigned int Conversation::getLastMessageId() +{ + return m_lastMessageId; +} + +bool Conversation::getResult() +{ + return m_result; +} + +} +} +} + diff --git a/src/platform/Tizen/Messaging/Conversation.h b/src/platform/Tizen/Messaging/Conversation.h new file mode 100755 index 0000000..d3f435d --- /dev/null +++ b/src/platform/Tizen/Messaging/Conversation.h @@ -0,0 +1,104 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** +* @file Conversation.h +* @author Kangsoo Lee (wpeter.lee@samsung.com) +* @version 0.1 +*/ + +#ifndef CONVERSATION_H +#define CONVERSATION_H + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { + + +class Conversation : public Api::Messaging::IConversation +{ +public: + Conversation(); + Conversation(unsigned int threadId, Api::Messaging::MessageType msgType); + Conversation(unsigned int threadIndex); + Conversation(std::string msgId, Api::Messaging::MessageType msgType); + + ~Conversation(); + + // getter + unsigned int getId(); + unsigned short getType(); + time_t getTime(); + unsigned long getMessageCount(); + unsigned long getUnreadMessages(); + std::string getPreview(); + std::string getSubject(); + bool getRead(); + std::string getFrom(); + std::vector getTo(); + std::vector getCC(); + std::vector getBCC(); + unsigned int getLastMessageId(); + bool getResult(); + bool makeConversationFromMsgId(unsigned int msgId, Api::Messaging::MessageType msgType); + void makeConversationFromThreadIndex(unsigned int threadIndex); + bool makeConversationFromEmailThreadId(unsigned int emailTreadId); +#if 0 + // setter + void setId(unsigned int id); + void setType(unsigned short type); + void setTime(time_t* time); + void setMessageCount(unsigned long messageCount); + void setUnreadMessages(unsigned long unreadMessages); + void setPreview(unsigned long unreadMessages); + void setRead(bool read); + void setFrom(std::string from); + void setTo(std::vector to); + void setCC(std::vector cc); + void setBCC(std::vector bcc); + void setLastMessageId(unsigned int id); +#endif + + +private: + unsigned int m_Id; + unsigned short int m_type; + time_t m_time; + unsigned long m_messageCount; + unsigned long m_unreadMessages; + std::string m_preview; + bool m_read; + std::string m_from; + std::string m_subject; + std::vector m_to; + std::vector m_cc; + std::vector m_bcc; + unsigned int m_lastMessageId; + bool m_result; + +}; +} +} +} + +#endif + diff --git a/src/platform/Tizen/Messaging/ConversationQueryGenerator.cpp b/src/platform/Tizen/Messaging/ConversationQueryGenerator.cpp new file mode 100755 index 0000000..5b95434 --- /dev/null +++ b/src/platform/Tizen/Messaging/ConversationQueryGenerator.cpp @@ -0,0 +1,127 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * ConversationQueryGenerator.cpp + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#include "ConversationQueryGenerator.h" +#include "API/Messaging/ConversationFilterValidatorFactory.h" + +#include +#include + +namespace TizenApis { + + namespace Platform { + namespace Messaging { + + const std::string ConversationQueryGenerator::QUERY_PREFIX_SMS_MMS = "WHERE (ADDRESS_ID <> 0) AND ("; + const std::string ConversationQueryGenerator::QUERY_PREFIX_EMAIL = "WHERE "; + const std::string ConversationQueryGenerator::QUERY_SUFFIX_SMS_MMS = ") "; + const std::string ConversationQueryGenerator::QUERY_SUFFIX_EMAIL = ""; + + const std::string ConversationQueryGenerator::STRING_DIRECTION = "MSG_DIRECTION"; + + ConversationQueryGenerator::ConversationQueryGenerator():MessageQueryGenerator() { + } + + ConversationQueryGenerator::ConversationQueryGenerator(const Api::Tizen::SortModePtr& sortMode, + const long limit, const long offset):MessageQueryGenerator(sortMode, limit, offset){ + + } + + ConversationQueryGenerator::~ConversationQueryGenerator() { + } + + void ConversationQueryGenerator::setSmsMmsAttributeMap(){ + LogDebug("<<<"); + attributeMap.clear(); + + attributeMap.insert( + std::pair( + ConversationFilterValidatorFactory::ATTRIBUTE_ID, "ADDRESS_ID")); + attributeMap.insert( + std::pair( + ConversationFilterValidatorFactory::ATTRIBUTE_TIMESTAMP, "MSG_TIME")); + attributeMap.insert( + std::pair( + ConversationFilterValidatorFactory::ATTRIBUTE_FROM, "ADDRESS_VAL")); + attributeMap.insert( + std::pair( + ConversationFilterValidatorFactory::ATTRIBUTE_TO, "ADDRESS_VAL")); + attributeMap.insert( + std::pair( + ConversationFilterValidatorFactory::ATTRIBUTE_PREVIEW, "MSG_TEXT")); + attributeMap.insert( + std::pair( + ConversationFilterValidatorFactory::ATTRIBUTE_MESSAGE_COUNT, "SMS_CNT+MMS_CNT")); + attributeMap.insert( + std::pair( + ConversationFilterValidatorFactory::ATTRIBUTE_UNREAD_MESSAGES, "UNREAD_CNT")); + + LogDebug(">>>"); + } + + std::string ConversationQueryGenerator::getMatchExactlyClause(std::string& attrName, Api::Tizen::AnyPtr& value){ + std::string retClause; + std::string emfAttributeName = convertToEmfAttrName(attrName); + + if(getMode() == MODE_SMS_MMS){ + if(attrName.compare(ConversationFilterValidatorFactory::ATTRIBUTE_MESSAGE_COUNT)==0){ + retClause = emfAttributeName + "=" + value->toString(); + return retClause; + }else if(attrName.compare(ConversationFilterValidatorFactory::ATTRIBUTE_PREVIEW)==0){ + retClause = emfAttributeName + " LIKE '" + value->toString() + "'"; + return retClause; + } + } + + retClause = MessageQueryGenerator::getMatchExactlyClause(attrName, value); + return retClause; + } + + std::string ConversationQueryGenerator::getQueryPrefix(){ + if(getMode() == MODE_EMAIL){ + return ConversationQueryGenerator::QUERY_PREFIX_EMAIL; + }else if(getMode() == MODE_SMS_MMS){ + return ConversationQueryGenerator::QUERY_PREFIX_SMS_MMS; + }else{ + MsgLogError("invalid mode:" << getMode()); + Throw(WrtDeviceApis::Commons::UnknownException); + } + } + + std::string ConversationQueryGenerator::getQuerySuffix(){ + if(getMode() == MODE_EMAIL){ + return ConversationQueryGenerator::QUERY_SUFFIX_EMAIL; + }else if(getMode() == MODE_SMS_MMS){ + return ConversationQueryGenerator::QUERY_SUFFIX_SMS_MMS; + }else{ + MsgLogError("invalid mode:" << getMode()); + Throw(WrtDeviceApis::Commons::UnknownException); + } + } + + std::string ConversationQueryGenerator::getMessageDirectionString(){ + return ConversationQueryGenerator::STRING_DIRECTION; + } + + } //Messaging + }// namespace Platform +} //namespace TizenApis diff --git a/src/platform/Tizen/Messaging/ConversationQueryGenerator.h b/src/platform/Tizen/Messaging/ConversationQueryGenerator.h new file mode 100755 index 0000000..c3bfde5 --- /dev/null +++ b/src/platform/Tizen/Messaging/ConversationQueryGenerator.h @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * ConversationQueryGenerator.h + * + * Created on: 2011. 10. 31. + * Author: sangtai + */ + +#ifndef CONVERSATIONQUERYGENERATOR_H_ +#define CONVERSATIONQUERYGENERATOR_H_ + +#include +#include "MessageQueryGenerator.h" + +namespace TizenApis { + + namespace Platform { + namespace Messaging { + + + class ConversationQueryGenerator : public MessageQueryGenerator{ + + public: + ConversationQueryGenerator(); + ConversationQueryGenerator(const Api::Tizen::SortModePtr& sortMode, const long limit, const long offset); + + virtual ~ConversationQueryGenerator(); + + protected: + virtual void setSmsMmsAttributeMap(); + virtual std::string getMatchExactlyClause(std::string& attrName, Api::Tizen::AnyPtr& value); + + virtual std::string getQueryPrefix(); + virtual std::string getQuerySuffix(); + + virtual std::string getMessageDirectionString(); + + private: + static const std::string QUERY_PREFIX_SMS_MMS; + static const std::string QUERY_PREFIX_EMAIL; + static const std::string QUERY_SUFFIX_SMS_MMS; + static const std::string QUERY_SUFFIX_EMAIL; + + static const std::string STRING_DIRECTION; + }; + + typedef DPL::SharedPtr ConversationQueryGeneratorPtr; + + } //Messaging + } //Platform +} //TizenApis + +#endif /* CONVERSATIONQUERYGENERATOR_H_ */ diff --git a/src/platform/Tizen/Messaging/Email.cpp b/src/platform/Tizen/Messaging/Email.cpp new file mode 100755 index 0000000..b47cf63 --- /dev/null +++ b/src/platform/Tizen/Messaging/Email.cpp @@ -0,0 +1,914 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Email.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Messaging.h" +#include "Email.h" +#include "EmailService.h" +#include "EmailUtils.h" +#include "EmailConverter.h" +#include "MailSender.h" +#include "MailSync.h" +#include "MessagingService.h" +#include "MessagingServiceManager.h" +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +#include "Attachment.h" +#endif + +#define LOG_ENTER LogDebug("---> ENTER"); +#define LOG_EXIT LogDebug("---> EXIT"); + +using namespace std; +using namespace TizenApis::Api::Messaging; +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +#if 0 // UNUSED CODE +namespace { +//#define USE_OUTBOX + +#ifdef USE_OUTBOX +const Api::Messaging::FolderType DEFAULT_FOLDER = Api::Messaging::OUTBOX; +const char* DEFAULT_FOLDER_NAME = EMF_OUTBOX_NAME; +#else +const Api::Messaging::FolderType DEFAULT_FOLDER = Api::Messaging::DRAFTBOX; +const char* DEFAULT_FOLDER_NAME = EMF_DRAFTBOX_NAME; +#endif +} +#endif + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +namespace { +const char* TEMP_FOLDER = "/tmp"; +const char* COMMAND_NAME = "/bin/cp"; +const char* COMMAND_SWITCH_RECURSIVE = "-r"; +const char* COMMAND_SWITCH_FORCE = "-f"; +} +#endif + +Email::Email(const string& id) : + IMessage(EMAIL, id) { + LOG_ENTER + + try { + if (getIdRef().empty()) { + create(); + } + // always read the message (after creation some of attributes change + // i.e. body->plain) + + //get account ID + + + reload(); + } catch (const WrtDeviceApis::Commons::PlatformException& ex) { + LogError("Exception: " << ex.DumpToString()); + } + + LOG_EXIT +} + +Email::Email(const std::string& id, int accountId) : + IMessage(EMAIL, id) +{ + LOG_ENTER + + try { + // always read the message (after creation some of attributes change + // i.e. body->plain) + + //get account ID + LogDebug("Account ID = " << accountId); + m_accountId = accountId; + reload(); + + } catch (const WrtDeviceApis::Commons::PlatformException& ex) { + LogError("Exception: " << ex.DumpToString()); + } + + + LOG_EXIT +} + +Email::Email(Api::Messaging::EmailAccountInfo& account) : IMessage(EMAIL) +{ + LOG_ENTER + + try { + if (getIdRef().empty()) { + create(account); + } + // always read the message (after creation some of attributes change + // i.e. body->plain) + reload(); + } + catch (const WrtDeviceApis::Commons::PlatformException& ex) { + LogError("Exception: " << ex.DumpToString()); + } + + LOG_EXIT +} + +Email::~Email() +{ + LogDebug("ENTER"); +} + +int Email::send() +{ + LOG_ENTER + + update(); + + int handle = MailSender::getInstance().send( + Api::Messaging::MessageFactory::convertToEmail(SharedFromThis()) + ); + + return handle; + LOG_EXIT +} + +void Email::sendCancel(int handle) +{ + LOG_ENTER + + MailSender::getInstance().cancel(handle); + + LOG_EXIT +} + +int Email::downloadBody() +{ + LOG_ENTER + + return MailSync::getInstance().downloadBody( Api::Messaging::MessageFactory::convertToEmail(SharedFromThis()) ); + + LOG_EXIT +} + +void Email::downloadBodyCancel( int handle) +{ + + return ; +} + +#if 0// MESSAGING ATTACHMENT IS BLOCKED +void Email::downloadAttachment( const Api::Messaging::IAttachmentPtr& attachment) +{ + LOG_ENTER + + MailSync::getInstance().downloadAttachment( Api::Messaging::MessageFactory::convertToEmail(SharedFromThis()), attachment ); + + LOG_EXIT +} +#endif + +void Email::update(bool draftsOnly) +{ + LOG_ENTER + + DPL::Mutex::ScopedLock mx(&m_updateMutex); + + if (!m_mail) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail is NULL."); + } + + LogDebug("getCurrentFolder() = " << getCurrentFolder() ); + if (!draftsOnly || (getCurrentFolder() == Api::Messaging::DRAFTBOX)) { + updateBody(); + updateSubject(); + updateRecipients(); + updateFrom(); +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + updateAttachments(); +#endif + updatePriority(); + } else { + LogWarning("Updating only read status. Folder: " << getCurrentFolder()); + } + updateReadStatus(); + + int error = email_update_message(getIntId(), m_mail.Get()); + if (EMF_ERROR_NONE != error) { + LogWarning("Nothing to update or error. [" << error << "]"); + } + + LOG_EXIT +} + +int Email::getAccountID() +{ + LOG_ENTER + + if ( m_mail ) + return m_mail->info->account_id; + else + return -1; + + LOG_EXIT +} + +int Email::getUID() +{ + LOG_ENTER + + if (m_mail) + return m_mail->info->uid; + else + return -1; + + LOG_EXIT +} + +int Email::isBodyDownloaded() +{ + + if (m_mail) + return m_mail->info->body_downloaded; + else + return false; +} + +void Email::readAllData() +{ + reload(); +} + +void Email::moveToFolder(const FolderType newFolder) +{ + LOG_ENTER + + moveToFolder(EmailConverter::toMailboxName(newFolder)); + + LOG_EXIT +} + +void Email::moveToFolder(const string& newFolder) +{ + update(); + + int accountId = Messaging::getInstance().getEmailAccountId(getFromRef()); + ScopedMailbox mailbox( + EmailService::createMailbox(accountId, newFolder.c_str()) + ); + + int mailId = getIntId(); + + int error = email_move_mail_to_mailbox(&mailId, 1, mailbox.Get()); + if (EMF_ERROR_NONE != error) { + ThrowMsg( + WrtDeviceApis::Commons::PlatformException, + "Couldn't move mail to folder: " << newFolder << ". [" << + error << "]"); + } +} + +void Email::copyToFolder(const FolderType newFolder) +{ + LOG_ENTER + + copyToFolder(EmailConverter::toMailboxName(newFolder)); + + LOG_EXIT +} + +void Email::copyToFolder(const string& newFolder) +{ + LOG_ENTER + + update(); + + int accountId = Messaging::getInstance().getEmailAccountId(getFromRef()); + + ScopedMail mail(EmailService::cloneMail(m_mail.Get())); + ScopedMailbox mailbox( + EmailService::createMailbox(accountId, newFolder.c_str()) + ); + + int mailId = EmailService::addMailToMailbox(mail.Get(), mailbox.Get()); + // TODO Is following check necessary? + if (0 == mailId) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Cloned mail didn't get new id."); + } + + LOG_EXIT +} + +void Email::remove() +{ + EmailService::deleteMail(m_accountId, getIntId()); +} + +void Email::create() +{ + LOG_ENTER + + EmailAccountInfo account = IMessaging::getInstance().getCurrentEmailAccount(); + m_accountId = account.getIntId(); + ScopedMail mail(EmailService::createMail(account)); + ScopedMailbox mailbox( + EmailService::getMailboxByType(account.getIntId(), + EMF_MAILBOX_TYPE_DRAFT) + ); + setId(convertId(EmailService::addMailToMailbox(mail.Get(), mailbox.Get()))); + setFolderType(Api::Messaging::DRAFTBOX); + setMessageStatus(Api::Messaging::MESSAGE_STATUS_DRAFT); + + LOG_EXIT +} + +void Email::create( Api::Messaging::EmailAccountInfo& account ) +{ + LOG_ENTER + + m_accountId = account.getIntId(); + MailSender::getInstance(); + + LogDebug("account ID : " << m_accountId); + ScopedMail mail(EmailService::createMail(account)); + ScopedMailbox mailbox(EmailService::getMailboxByType(account.getIntId(), EMF_MAILBOX_TYPE_DRAFT)); + setId(convertId(EmailService::addMailToMailbox(mail.Get(), mailbox.Get()))); + setFolderType(Api::Messaging::DRAFTBOX); + setMessageStatus(Api::Messaging::MESSAGE_STATUS_DRAFT); + + LOG_EXIT +} + +void Email::reload() +{ + LOG_ENTER + + //EmailAccountInfo account = Messaging::getInstance().getCurrentEmailAccount(); + LogDebug("account ID :" << m_accountId); + m_mail.Reset(EmailService::readMail(m_accountId, getIntId())); + + if (m_mail->head) { readHeader(); } + if (m_mail->body) { readBody(); } + if (m_mail->info) { readInfo(); } + + m_mailbox.Reset(EmailService::getMailboxByMailId(m_accountId, getIntId()) ); + setFolderType(EmailConverter::toFolderType(m_mailbox->mailbox_type)); + + LOG_EXIT +} + +void Email::readHeader() +{ + LOG_ENTER + + Assert(m_mail && m_mail->head && "Header is NULL."); + + if (m_mail->head->subject) { + setSubject(m_mail->head->subject); + } + + if (m_mail->head->to) { + appendToRecipients(EmailUtils::stripAddressLine(m_mail->head->to)); + } + + if (m_mail->head->cc) { + appendCcRecipients(EmailUtils::stripAddressLine(m_mail->head->cc)); + } + + if (m_mail->head->bcc) { + appendBccRecipients(EmailUtils::stripAddressLine(m_mail->head->bcc)); + } + + time_t rawtime; + time(&rawtime); + struct tm tmpTime = *(localtime(&rawtime)); + tmpTime.tm_year = m_mail->head->datetime.year; + tmpTime.tm_mon = m_mail->head->datetime.month; + tmpTime.tm_mday = m_mail->head->datetime.day; + tmpTime.tm_hour = m_mail->head->datetime.hour; + tmpTime.tm_min = m_mail->head->datetime.minute; + tmpTime.tm_sec = m_mail->head->datetime.second; + mktime(&tmpTime); + setDateTime(tmpTime); + + if (m_mail->head->from) { + Recipients from; + from.setRecipients(m_mail->head->from); + setSourceAddress(from); + setSourceAddressValidity(true); //not needed to update in platform + } + + LOG_EXIT +} + +void Email::readBody() { + LOG_ENTER + + Assert(m_mail && m_mail->body && "Body is NULL."); + + if (m_mail->body->plain) { + DPL::ScopedFClose file(::fopen(m_mail->body->plain, "r")); + if (!file) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Cannot read body file: " << m_mail->body->plain); + } + fseek(file.Get(), 0, SEEK_END); + long int size = ftell(file.Get()); + fseek(file.Get(), 0, SEEK_SET); + DPL::ScopedPtr data(new char[size + 1]); + memset(data.Get(), 0, size + 1); + fread(data.Get(), 1, size, file.Get()); + setBody(data.Get()); + } + + //html body. + if (m_mail->body->html) { + DPL::ScopedFClose file(::fopen(m_mail->body->html, "r")); //auto close, scopedFClose + if (!file) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Cannot read html body file: " << m_mail->body->html); + } + + fseek(file.Get(), 0, SEEK_END); + long int size = ftell(file.Get()); + fseek(file.Get(), 0, SEEK_SET); + DPL::ScopedPtr data(new char[size + 1]); + memset(data.Get(), 0, size + 1); + fread(data.Get(), 1, size, file.Get()); + setHtmlBody(data.Get()); //setHtmlBody declarate in Email Calss. + } +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + if (m_mail->body->attachment && m_mail->body->attachment_num > 0) { + LogDebug("reading attachments , attahcment count = " << m_mail->body->attachment_num); + emf_attachment_info_t* attach = m_mail->body->attachment; + for (int i = 0; i < m_mail->body->attachment_num; ++i) { + if (!attach) { + LogDebug("throw platform exception"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Attachment list shorter than expected."); + } + + try { + + LogError("id :" << attach->attachment_id << " name :" << attach->name << " download :" << attach->downloaded << " savefile :" << attach->savename ); + + IAttachmentPtr tmpAtt(new Attachment(attach)); + LogError(" create new attachment "); + if (tmpAtt) + { + //tmpAtt->setMessage(SharedFromThis()); //set IMessagePtr + tmpAtt->rename(attach->name); + tmpAtt->setAttachmentID(attach->attachment_id); + tmpAtt->setDownloaded(attach->downloaded); + tmpAtt->setNth(i+1); + appendAttachment(tmpAtt); + LogError(" append complete"); + } + +#if 0 + if( (attach->name != NULL && !attach->downloaded)) + { + + } + else if (attach->savename != NULL) + { + tmpAtt = appendAttachment(attach->savename, false); + } + + + + + IAttachmentPtr tmpAtt; + if( (attach->name != NULL && !attach->downloaded)) + { + IAttachmentPtr tAtt(new Attachment(attach)); + appendAttachment(tmpAtt); + tmpAtt = tAtt; + } + else if (attach->savename != NULL) + { + tmpAtt = appendAttachment(attach->savename, false); + } + + /* + if(attach->savename != NULL){ + tmpAtt = appendAttachment(attach->savename, false); + + } + */ + if (tmpAtt) + { + //tmpAtt->setMessage(IMessagePtr(this)); //set IMessagePtr + //IMessagePtr msg = DPL::DynamicPointerCast(this); + tmpAtt->setMessage(SharedFromThis()); //set IMessagePtr + tmpAtt->rename(attach->name); + tmpAtt->setAttachmentID(attach->attachment_id); + tmpAtt->setDownloaded(attach->downloaded); + } + +#endif + + attach = attach->next; + } + catch (const WrtDeviceApis::Commons::Exception& ex) { + LogError("Error while trying to append attachment " << + attach->savename << ": " << ex.DumpToString()); + } + } + } +#endif + LOG_EXIT +} + +void Email::readInfo() +{ + LOG_ENTER + + Assert(m_mail && m_mail->info && "Info is NULL."); + + setReadStatus(m_mail->info->flags.seen == 1); + + m_accountId = m_mail->info->account_id; + + setPriority( + EmailConverter::toMessagePriority( m_mail->info->extra_flags.priority ) + ); + setSize(m_mail->info->rfc822_size); + + LOG_EXIT +} + +void Email::updateBody() +{ + LOG_ENTER + + if (isBodyValid()) { return; } + + if (!m_mail) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail is NULL."); + } + + if (!m_mail->body) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Body is NULL."); + } + if (!m_mail->body->plain) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Body file is NULL."); + } + + if (!m_mail->body->html) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Html Body file is NULL."); + } + + if (!m_mail->info) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Info is NULL."); + } + + //update plain body. + FILE* f = fopen(m_mail->body->plain, "w"); + if (NULL != f) { + //fprintf(f, getBodyRef().c_str()); + fwrite(getBodyRef().c_str(), strlen(getBodyRef().c_str()), 1, f); + fclose(f); + } + else + { + LogDebug("Plain Body file is NULL."); + } + + if (m_mail->body->html) { + //update html body + f = fopen(m_mail->body->html, "w"); + if (NULL != f) { + //fprintf(f, getHtmlBody().c_str()); + fwrite(getHtmlBody().c_str(), strlen(getHtmlBody().c_str()), 1, f); + fclose(f); + } + } + else + { + LogDebug("Html Body file is NULL."); + } + + m_mail->info->body_downloaded = true; + setBodyValidity(true); + + LOG_EXIT +} + +void Email::updateSubject() +{ + LOG_ENTER + + if (isSubjectValid()) { return; } + + LogDebug("update subject, msgId=" << getIdRef()); + + if (!m_mail) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail not allocated."); + } + + if (!m_mail->head) { + m_mail->head = EmailService::alloc(); + } + + m_mail->head->subject = String::strdup(getSubjectRef()); + setSubjectValidity(true); + + LOG_EXIT +} + +void Email::updateReadStatus() +{ + LOG_ENTER + + if (isReadStatusValid()) { return; } + + LogDebug("update read, msgId=" << getIdRef()); + + if (!m_mail) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail not allocated."); + } + + if (!m_mail->info) { + EmailService::alloc(); + } + + m_mail->info->flags.seen = isRead(); + setReadStatusValidity(true); + + LOG_EXIT +} + +void Email::updateIsRead() +{ + LOG_ENTER + if (isReadChangeStatusValid()) { + // do not update if not changed + return; + } + + EmailService::updateSeenFlag(getAccountID(), getIntId(), isReadChangeStatus()); + setisReadChangeStatusValidity(true); + LOG_EXIT +} + +void Email::updateRecipients() +{ + LOG_ENTER + + if (getToValidity() && getCcValidity() && getBccValidity()) { return; } + + if (!m_mail) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail is NULL."); + } + + if (!m_mail->head) { + m_mail->head = EmailService::alloc(); + } + + if (!getToValidity()) { + std::string addressLine = EmailUtils::formatAddressLine(getToRecipients()); + if (m_mail->head->to) { + free(m_mail->head->to); + } + m_mail->head->to = String::strdup(addressLine); + setToValidity(true); + } + + if (!getCcValidity()) { + std::string addressLine = EmailUtils::formatAddressLine(getCcRecipients()); + if (m_mail->head->cc) { + free(m_mail->head->cc); + } + m_mail->head->cc = String::strdup(addressLine); + setCcValidity(true); + } + + if (!getBccValidity()) { + std::string addressLine = EmailUtils::formatAddressLine( + getBccRecipients()); + if (m_mail->head->bcc) { + free(m_mail->head->bcc); + } + m_mail->head->bcc = String::strdup(addressLine); + setBccValidity(true); + } + + LOG_EXIT +} + +void Email::updateFrom() +{ + LOG_ENTER + + if (getFromValidity()) { return; } + + if (!m_mail) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail is NULL."); + } + + if (!m_mail->info) { + EmailService::alloc(); + } + + m_mail->info->account_id = m_accountId; + // TODO Update m_mail->head->from as well + + setFromValidity(true); + + LOG_EXIT +} + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +void Email::updateAttachments() +{ + LOG_ENTER + + if (isAttachmentsValid()) { return; } + + if (!m_mail) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail is NULL."); + } + + emf_attachment_info_t* attachment = NULL; + Try { + LogDebug("update attachments, msgId=" << getIdRef()); + + if (!m_mail->body) { + m_mail->body = EmailService::alloc(); + } else { + //clean attachment + int i = m_mail->body->attachment_num; + LogDebug("clean attachment, attachment count=" << i); + attachment = m_mail->body->attachment; + std::stringstream stream; + + while(attachment) + { + LogDebug("delete file :" << attachment->name << " saved name :" << attachment->savename ); + int aId = attachment->attachment_id; + char* mId = m_mail->head->mid; + int n_mId = 0; + stream << mId; + stream >> n_mId; + stream << aId; + + LogDebug("mID :" << n_mId << " Attachment Id :" << aId ); + + int error = email_delete_attachment(m_mailbox.Get(), n_mId, (const char*)(stream.str()).c_str()); + if (EMF_ERROR_NONE != error) { + LogDebug("Error Num = " << error); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Error while adding attachment. [" << error << "]"); + } + attachment = attachment->next; + } + + m_mail->body->attachment_num = 0; + if (NULL != m_mail->body->attachment) { + EmailService::freeAttachment(m_mail->body->attachment); + m_mail->body->attachment = NULL; + } + } + + std::size_t attachmentSize = getAttachmentsCount(); + LogDebug("update attachments, attachmentSize=" << attachmentSize); + if (attachmentSize > 0) { + if (!m_mail->info) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail info is NULL."); + } + + for (std::size_t i = 0; i < attachmentSize; ++i) { + IAttachmentPtr att = getAttachment(i); + if (!att) { + continue; + } + + //copy attachment file + std::stringstream to_oss; + to_oss << TEMP_FOLDER << "/" << att->getShortName(); + LogDebug("temp file=" << to_oss.str()); + + std::stringstream cp_oss; + cp_oss << COMMAND_NAME; + cp_oss << " " << COMMAND_SWITCH_RECURSIVE; + cp_oss << " \"" << att->getFullPath() << "\""; + cp_oss << " \"" << to_oss.str() << "\""; + + attachment = EmailService::alloc(); //create attachment struct + attachment->name = String::strdup(att->getShortName()); + //attachment->savename = String::strdup( att->getFullPath() ); + attachment->savename = String::strdup( to_oss.str().c_str() ); + + attachment->next = NULL; + attachment->downloaded = true; + + int result = system(cp_oss.str().c_str()); + if (-1 != result) { + if (0 != WIFEXITED(result)) { + if (0 != WEXITSTATUS(result)) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Command failed."); + } + } else { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Command terminated abnormally."); + } + } else { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Couldn't launch command."); + } + + LogDebug( "mailbox type = " << m_mailbox.Get()->mailbox_type); + + int error = email_add_attachment(m_mailbox.Get(), + m_mail->info->uid, + attachment); + if (EMF_ERROR_NONE != error) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Error while adding attachment. [" << error << "]"); + } + else + { + LogDebug(" attachment id : " << attachment->attachment_id); + //IMessagePtr msg = DPL::DynamicPointerCast(this); + att->setDownloaded(true); + att->setAttachmentID(attachment->attachment_id); + att->setMessage(SharedFromThis()); + att->setNth(i+1); + } + + EmailService::freeAttachment(attachment); + } + + setAttachmentsValidity(true); + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + EmailService::freeAttachment(attachment); + throw; + } + + LOG_EXIT +} +#endif + +void Email::updatePriority() +{ + LOG_ENTER + + if (isPriorityValid()) { return; } + + if (!m_mail) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail not allocated."); + } + + if (!m_mail->info) { + m_mail->info = EmailService::alloc(); + } + + m_mail->info->extra_flags.priority = EmailConverter::toMailPriority( + getPriority()); + setPriorityValid(true); + + LOG_EXIT +} + +int Email::getIntId() const +{ + return convertId(getIdRef()); +} +} +} +} diff --git a/src/platform/Tizen/Messaging/Email.h b/src/platform/Tizen/Messaging/Email.h new file mode 100755 index 0000000..babc3ce --- /dev/null +++ b/src/platform/Tizen/Messaging/Email.h @@ -0,0 +1,143 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Email.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef EMAIL_H +#define EMAIL_H + +#include +#include +#include +#include +#include + +#include "ScopedMail.h" +#include "ScopedMailbox.h" + +// The email service library +extern "C" { +//temporary solution for email-service problem (compilation break) +#ifndef NOW_REVERT +//#define NOW_REVERT +#endif +#ifndef SUPPORT_CONTACT_ON_SIM +//#define SUPPORT_CONTACT_ON_SIM +#endif +#ifndef _A_PROJECT_ +#define _A_PROJECT_ +#endif + +#ifndef _PREVIEW_IN_MAILIST +#define _PREVIEW_IN_MAILIST +#endif +} + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +class Email : public Api::Messaging::IEmail +{ + public: + explicit Email(const std::string& id = std::string()); + + explicit Email(const std::string& id, int accountId); + + explicit Email( Api::Messaging::EmailAccountInfo& account); + + virtual ~Email(); + + virtual int send(); + + virtual void sendCancel(int handle); + + virtual int downloadBody(); + + virtual void downloadBodyCancel( int handle ); +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + virtual void downloadAttachment(const Api::Messaging::IAttachmentPtr& attachment); +#endif + + // implementation of interface of IMessage class + virtual void update(bool draftsOnly = false); + + virtual void readAllData(); + + virtual void moveToFolder(const Api::Messaging::FolderType newFolder); + + virtual void moveToFolder(const std::string& newFolder); + + virtual void copyToFolder(const Api::Messaging::FolderType newFolder); + + virtual void copyToFolder(const std::string& newFolder); + + virtual void remove(); + + virtual int getAccountID(); + + virtual int getUID(); + + virtual int isBodyDownloaded(); + + private: + void create(); + + void create( Api::Messaging::EmailAccountInfo& account ); + + void reload(); + + void readHeader(); + + void readBody(); + + void readInfo(); + + void updateBody(); + + void updateRecipients(); + + void updateFrom(); +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + void updateAttachments(); +#endif + void updateSubject(); + + void updateReadStatus(); + + void updateIsRead(); + + void updatePriority(); + + int getIntId() const; + + private: + DPL::Mutex m_updateMutex; + int m_accountId; + ScopedMail m_mail; + ScopedMailbox m_mailbox; +}; +} +} +} +#endif diff --git a/src/platform/Tizen/Messaging/EmailConverter.cpp b/src/platform/Tizen/Messaging/EmailConverter.cpp new file mode 100755 index 0000000..eb2baf6 --- /dev/null +++ b/src/platform/Tizen/Messaging/EmailConverter.cpp @@ -0,0 +1,119 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ +#include + +#include + +#include "EmailConverter.h" + +#define LOG_ENTER LogDebug("---> ENTER"); +#define LOG_EXIT LogDebug("---> EXIT"); + +namespace TizenApis { +namespace Platform { +namespace Messaging { +namespace EmailConverter { +emf_mail_priority_t toMailPriority(Api::Messaging::MessagePriority::Priority priority) +{ + LOG_ENTER + switch (priority) { + case Api::Messaging::MessagePriority::LOW: return EMF_MAIL_PRIORITY_LOW; + case Api::Messaging::MessagePriority::NORMAL: return EMF_MAIL_PRIORITY_NORMAL; + case Api::Messaging::MessagePriority::HIGH: return EMF_MAIL_PRIORITY_HIGH; + default: + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Unsupported priority: " << priority); + } +} + +Api::Messaging::MessagePriority::Priority toMessagePriority(emf_mail_priority_t priority) +{ + LOG_ENTER + switch (priority) { + case EMF_MAIL_PRIORITY_LOW: return Api::Messaging::MessagePriority::LOW; + case EMF_MAIL_PRIORITY_NORMAL: return Api::Messaging::MessagePriority::NORMAL; + case EMF_MAIL_PRIORITY_HIGH: return Api::Messaging::MessagePriority::HIGH; + default:{ + // TODO Think it through, log is enough or exception should be thrown. + // ThrowMsg(WrtDeviceApis::Commons::PlatformException, + // "Unsupported platform priority: " << priority); + LogWarning("Unsupported platform priority"); + } + } + + // TODO Fix this. What to return if non-existing priority returned by platform. + return Api::Messaging::MessagePriority::NORMAL; +} + +Api::Messaging::MessagePriority::Priority toMessagePriority(unsigned char priority) +{ + return toMessagePriority(static_cast(priority)); +} + +emf_mailbox_type_e toMailboxType(Api::Messaging::FolderType folder) +{ + LOG_ENTER + switch (folder) { + case Api::Messaging::INBOX: return EMF_MAILBOX_TYPE_INBOX; + case Api::Messaging::OUTBOX: return EMF_MAILBOX_TYPE_OUTBOX; + case Api::Messaging::SENTBOX: return EMF_MAILBOX_TYPE_SENTBOX; + case Api::Messaging::DRAFTBOX: return EMF_MAILBOX_TYPE_DRAFT; + case Api::Messaging::SPAMBOX: return EMF_MAILBOX_TYPE_SPAMBOX; + case Api::Messaging::ALL_FOLDERS: return EMF_MAILBOX_TYPE_ALL_EMAILS; + case Api::Messaging::USERDEFINED_FOLDER: return EMF_MAILBOX_TYPE_USER_DEFINED; + default: + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Conversion failed."); + } +} + +const char* toMailboxName(Api::Messaging::FolderType folder) +{ + LOG_ENTER + switch (folder) { + case Api::Messaging::INBOX: return EMF_INBOX_NAME; + case Api::Messaging::OUTBOX: return EMF_OUTBOX_NAME; + case Api::Messaging::SENTBOX: return EMF_SENTBOX_NAME; + case Api::Messaging::DRAFTBOX: return EMF_DRAFTBOX_NAME; + case Api::Messaging::SPAMBOX: return EMF_SPAMBOX_NAME; + default: + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Mailbox not found. Folder: " << folder); + } +} + +Api::Messaging::FolderType toFolderType(emf_mailbox_type_e mailboxType) +{ + LOG_ENTER + switch (mailboxType) { + case EMF_MAILBOX_TYPE_INBOX: return Api::Messaging::INBOX; + case EMF_MAILBOX_TYPE_OUTBOX: return Api::Messaging::OUTBOX; + case EMF_MAILBOX_TYPE_SENTBOX: return Api::Messaging::SENTBOX; + case EMF_MAILBOX_TYPE_DRAFT: return Api::Messaging::DRAFTBOX; + case EMF_MAILBOX_TYPE_SPAMBOX: return Api::Messaging::SPAMBOX; + case EMF_MAILBOX_TYPE_ALL_EMAILS: return Api::Messaging::ALL_FOLDERS; + case EMF_MAILBOX_TYPE_USER_DEFINED: return Api::Messaging::USERDEFINED_FOLDER; + default: + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Conversion failed."); + } +} +} +} +} +} diff --git a/src/platform/Tizen/Messaging/EmailConverter.h b/src/platform/Tizen/Messaging/EmailConverter.h new file mode 100755 index 0000000..7d50c44 --- /dev/null +++ b/src/platform/Tizen/Messaging/EmailConverter.h @@ -0,0 +1,43 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef _TIZEN_MESSAGING_EMAILCONVERTER_H_ +#define _TIZEN_MESSAGING_EMAILCONVERTER_H_ + +#include + +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { +namespace EmailConverter { +emf_mail_priority_t toMailPriority(Api::Messaging::MessagePriority::Priority priority); + +Api::Messaging::MessagePriority::Priority toMessagePriority(emf_mail_priority_t priority); +Api::Messaging::MessagePriority::Priority toMessagePriority(unsigned char priority); + +emf_mailbox_type_e toMailboxType(Api::Messaging::FolderType folder); + +const char* toMailboxName(Api::Messaging::FolderType folder); + +Api::Messaging::FolderType toFolderType(emf_mailbox_type_e mailboxType); +} +} +} +} +#endif diff --git a/src/platform/Tizen/Messaging/EmailService.cpp b/src/platform/Tizen/Messaging/EmailService.cpp new file mode 100755 index 0000000..fd6a9e9 --- /dev/null +++ b/src/platform/Tizen/Messaging/EmailService.cpp @@ -0,0 +1,225 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ +#include +#include + +#include +#include + +#include + +#include +#include "EmailUtils.h" +#include "EmailService.h" +#include "ScopedMail.h" +#include "ScopedMailbox.h" + +#define LOG_ENTER LogDebug("---> ENTER"); +#define LOG_EXIT LogDebug("---> EXIT"); + +namespace TizenApis { +namespace Platform { +namespace Messaging { +namespace EmailService { +emf_mail_t* createMail(const Api::Messaging::EmailAccountInfo& account) +{ + LOG_ENTER + ScopedMail result(alloc()); + + result->info = alloc(); + result->info->account_id = account.getIntId(); + result->info->flags.draft = 1; + result->info->extra_flags.priority = EMF_MAIL_PRIORITY_NORMAL; + + result->head = alloc(); + std::string from = EmailUtils::formatAddress(account.getAddress(), + account.getName()); + result->head->from = strdup(from.c_str()); + + result->body = alloc(); + std::string bodyFile = tmpnam(NULL); + + FILE* f = fopen(bodyFile.c_str(), "w"); + fclose(f); + result->body->plain = strdup(bodyFile.c_str()); + std::string htmlFile = tmpnam(NULL); + + f = fopen(htmlFile.c_str(), "w"); + fclose(f); + result->body->html = strdup(htmlFile.c_str()); + + LOG_EXIT + return result.Release(); +} + +emf_mail_t* readMail(int accountId, + int mailId) +{ + LOG_ENTER + emf_mail_t* result = NULL; + + emf_mailbox_t mailbox = {}; + mailbox.account_id = accountId; + + int error = email_get_mail(&mailbox, mailId, &result); + if (EMF_ERROR_NONE != error) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Couldn't find message " << mailId << ". [" << error << "]"); + } + + LOG_EXIT + return result; +} + +void deleteMail(int accountId, + int mailId) +{ + LOG_ENTER + emf_mailbox_t mailbox = {}; + mailbox.account_id = accountId; + + int error = email_delete_message(&mailbox, &mailId, 1, 0); + if (EMF_ERROR_NONE != error) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Error while deleting mail. [" << error << "]"); + } + LOG_EXIT +} + +emf_mailbox_t* getMailboxByType(int accountId, + emf_mailbox_type_e type) +{ + LOG_ENTER + emf_mailbox_t* result = NULL; + + int error = email_get_mailbox_by_mailbox_type(accountId, type, &result); + if (EMF_ERROR_NONE != error) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Couldn't retrieve mailbox. [" << error << "]"); + } + + LOG_ENTER + return result; +} + +int addMailToMailbox(emf_mail_t* mail, + emf_mailbox_t* mailbox) +{ + LOG_ENTER + Assert(mail && mailbox); + + int error = email_add_message(mail, mailbox, 1); + if (EMF_ERROR_NONE != error) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Couldn't add message to mailbox. [" << error << "]"); + } + + LOG_EXIT + return mail->info->uid; +} + +void freeAttachment(emf_attachment_info_t* attachment) +{ + LOG_ENTER + if (NULL == attachment) { return; } + + int error = email_free_attachment_info(&attachment); + if (EMF_ERROR_NONE != error) { + LogWarning("Couldn't free attachment. [" << error << "]"); + } + LOG_ENTER +} + +emf_mailbox_t* createMailbox(int accountId, + const char* name) +{ + LOG_ENTER + emf_mailbox_t* result = alloc(); + result->account_id = accountId; + result->name = (NULL != name ? strdup(name) : NULL); + + LOG_EXIT + return result; +} + +// TODO This clonning is not efficent. +emf_mail_t* cloneMail(const emf_mail_t* mail) +{ + LOG_ENTER + emf_mail_t* result = readMail(mail->info->account_id, mail->info->uid); + result->info->uid = 0; + + LOG_EXIT + return result; +} + +emf_mailbox_t* getMailboxByMailId(int accountId, + int mailId) +{ + LOG_ENTER + char* mailboxName = NULL; + int error = email_get_mailbox_name_by_mail_id(mailId, &mailboxName); + // Platform may allocate mailboxName and yet return an error code. + DPL::ScopedFree freeGuard(mailboxName); + if (EMF_ERROR_NONE != error) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Couldn't get mailbox name. [" << error << "]"); + } + + emf_mailbox_t* result = NULL; + error = email_get_mailbox_by_name(accountId, mailboxName, &result); + if (EMF_ERROR_NONE != error) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Couldn't get mailbox. [" << error << "]"); + } + + LOG_EXIT + return result; +} + +void updateSeenFlag(int accountId, int mailId, bool isReadChangeStatus) +{ + LOG_ENTER + + + if ( accountId > -1 ) + { + if (EMF_ERROR_NONE != + email_set_flags_field(accountId, &mailId, 0, EMF_FLAGS_SEEN_FIELD, isReadChangeStatus, 1) ) + { + LogWarning("email_modify_seen_flag failed\n"); + } + else + { + LogWarning("email_modify_seen_flag SUCCESS\n"); + } + } + else + { + LogWarning("Invaild Account ID\n"); + } + + LOG_EXIT +} + +} +} +} +} diff --git a/src/platform/Tizen/Messaging/EmailService.h b/src/platform/Tizen/Messaging/EmailService.h new file mode 100755 index 0000000..884a81c --- /dev/null +++ b/src/platform/Tizen/Messaging/EmailService.h @@ -0,0 +1,78 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef TIZEN_MESSAGING_EMAILSERVICE_H_ +#define TIZEN_MESSAGING_EMAILSERVICE_H_ + +#include +#include +#include + +#include + +#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +namespace EmailService { +template +T* alloc() +{ + T* result = static_cast(::malloc(sizeof(T))); + if (NULL == result) { + throw std::bad_alloc(); + } + ::memset(result, 0, sizeof(*result)); + return result; +} + +emf_mail_t* createMail(const Api::Messaging::EmailAccountInfo& account); + +emf_mail_t* readMail(int accountId, + int mailId); + +emf_mailbox_t* getMailboxByType(int accountId, + emf_mailbox_type_e type); + +int addMailToMailbox(emf_mail_t* mail, + emf_mailbox_t* mailbox); + +void deleteMail(int accountId, + int mailId); + +void freeAttachment(emf_attachment_info_t* attachment); + +emf_mailbox_t* createMailbox(int accountId, + const char* name); + +emf_mail_t* cloneMail(const emf_mail_t* mail); + +emf_mailbox_t* getMailboxByMailId(int accountId, + int mailId); + +void updateSeenFlag(int accountId, int mailId, bool isReadChangeStatus); + +} +} +} +} +#endif diff --git a/src/platform/Tizen/Messaging/EmailUtils.cpp b/src/platform/Tizen/Messaging/EmailUtils.cpp new file mode 100755 index 0000000..cf3371d --- /dev/null +++ b/src/platform/Tizen/Messaging/EmailUtils.cpp @@ -0,0 +1,96 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ +#include +#include + +#include +#include +#include +#include "EmailUtils.h" + +using namespace WrtDeviceApis::Commons; + +namespace { +const char* EMAIL_ADDRESS_REGEX = + "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}"; + +const std::string EMAIL_ADDRESS_REGEX_GROUP = + StringBuilder() + .append("(") + .append(EMAIL_ADDRESS_REGEX) + .append(")") + .toString(); +} +namespace TizenApis { +namespace Platform { +namespace Messaging { +namespace EmailUtils { +std::string formatAddress(const std::string& address, + const std::string& name) +{ + if (address.empty()) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Address is empty."); + } + + std::stringstream ss; + if (!name.empty()) { + ss << "\"" << name << "\" "; + } + ss << "<" << address << ">"; + + return ss.str(); +} + +std::string formatAddressLine(const Api::Messaging::Recipients& recipients) +{ + std::string result; + for (size_t i = 0; i < recipients.getRecipientSize(); ++i) { + result += formatAddress(recipients.getRecipient(i)) + ";"; + } + return result; +} + +std::string stripAddress(const std::string& address) +{ + std::string result; + pcrecpp::RE re(EMAIL_ADDRESS_REGEX_GROUP); + if (!re.PartialMatch(address, &result)) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Couldn't discover email address"); + } + return result; +} + +Api::Messaging::Recipients stripAddressLine(const std::string& addressLine) +{ + typedef std::vector Addresses; + + Api::Messaging::Recipients result; + Addresses addresses = String::split(addressLine, ';'); + for (Addresses::iterator it = addresses.begin(); + it != addresses.end(); + ++it) { + result.appendRecipient(stripAddress(*it)); + } + return result; +} +} +} +} +} diff --git a/src/platform/Tizen/Messaging/EmailUtils.h b/src/platform/Tizen/Messaging/EmailUtils.h new file mode 100755 index 0000000..61f3df1 --- /dev/null +++ b/src/platform/Tizen/Messaging/EmailUtils.h @@ -0,0 +1,66 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef TIZEN_MESSAGING_EMAILUTILS_H_ +#define TIZEN_MESSAGING_EMAILUTILS_H_ + +#include + +#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +namespace EmailUtils { +/** + * Formats address as: "Name"
. + * @param address E-mail address. + * @param name Name, omitted if empty. + * @return Formatted address. + */ +std::string formatAddress(const std::string& address, + const std::string& name = std::string()); + +/** + * Formats multiple addresses as: "Name1" ;"Name2" ... + * @param recipients Recipients to build address line from. + * @return Formatted addresses. + */ +std::string formatAddressLine(const Api::Messaging::Recipients& recipients); + +/** + * Extracts bare e-mail address. + * @param address Address to strip. + * @return E-mail address. + */ +std::string stripAddress(const std::string& address); + +/** + * Extracts recipients bare e-mail addresses. + * @param addressLine Address line to split and strip. + * @return Recipients. + */ +Api::Messaging::Recipients stripAddressLine(const std::string& addressLine); +} +} +} +} +#endif diff --git a/src/platform/Tizen/Messaging/FolderQueryGenerator.cpp b/src/platform/Tizen/Messaging/FolderQueryGenerator.cpp new file mode 100644 index 0000000..5655126 --- /dev/null +++ b/src/platform/Tizen/Messaging/FolderQueryGenerator.cpp @@ -0,0 +1,201 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * FolderQueryGenerator.cpp + * + * Created on: 2011. 10. 28. + * Author: sangtai + */ + +#include "FolderQueryGenerator.h" +#include "API/Messaging/FolderFilterValidatorFactory.h" +#include "API/Messaging/ConversationFilterValidatorFactory.h" + +#include +#include +#include + +#include + +#include + +using namespace std; +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + + namespace Platform { + namespace Messaging { + + const std::string FolderQueryGenerator::STRING_MATCH_EXACTLY = "EXACTLY"; + const std::string FolderQueryGenerator::STRING_MATCH_CONTAINS = "CONTAINS"; + const std::string FolderQueryGenerator::STRING_MATCH_STARTSWITH = "STARTSWITH"; + const std::string FolderQueryGenerator::STRING_MATCH_ENDSWITH = "ENDSWITH"; +// const std::string FolderQueryGenerator::STRING_MATCH_CASESENSITIVE = "CASESENSITIVE"; + + const int FolderQueryGenerator::ACCOUNT_ID_NOT_INITIALIZED = -1; + + FolderQueryGenerator::FolderQueryGenerator():m_messageType(ACCOUNT_ID_NOT_INITIALIZED) { + } + + FolderQueryGenerator::~FolderQueryGenerator() { + } + + + void FolderQueryGenerator::visitPreComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + } + + void FolderQueryGenerator::visitInComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + + if(type != INTERSECTION_FILTER){ + LogError("[ERROR] >>> invalid Filter type:" << type); + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "invalid Fiilter Type"); + return; + } + } + + void FolderQueryGenerator::visitPostComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + } + + bool FolderQueryGenerator::getMatchExactlyClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string retClause; + std::string valueString = value->toString(); + + do{ + if(attrName.compare(FolderFilterValidatorFactory::ATTRIBUTE_ACCOUNTID)==0){ + m_accountId = atoi(value->toString().c_str()); + break; + }else if(attrName.compare(FolderFilterValidatorFactory::ATTRIBUTE_FOLDERPATH)==0){ + m_folderPathProcessing = TRUE; + m_folderpath = value->toString(); + break; + } + }while(false); + + return FALSE; + } + + std::string FolderQueryGenerator::getMatchStartsWithClause(std::string& attrName, TizenApis::Api::Tizen::AnyPtr& value){ + std::string retClause; + LogDebug("<<< NOT IMPLEMENTED YET"); + return retClause; + } + + std::string FolderQueryGenerator::getMatchEndsWithClause(std::string& attrName, TizenApis::Api::Tizen::AnyPtr& value){ + std::string retClause; + LogDebug("<<< NOT IMPLEMENTED YET"); + return retClause; + } + + std::string FolderQueryGenerator::getMatchContainsClause(std::string& attrName, TizenApis::Api::Tizen::AnyPtr& value){ + std::string retClause; + LogDebug("<<< NOT IMPLEMENTED YET"); + return retClause; + } + + void FolderQueryGenerator::visitAttribute(std::string& attrName, + Api::Tizen::AnyArrayPtr& values, std::string& matchFlag, bool caseSensitive, int depth){ + LogDebug("<<< attrName:[" << attrName << "], matchFlag:[" << matchFlag << "]"); + LogDebug("values->size():" << values->size()); + + Api::Tizen::FilterType filterType = UNION_FILTER; + + if(matchFlag.compare("EXIST")==0){ + //TODO implement for EXIST + }else if(values->size() == 1){ + AnyPtr matchValue = values->at(0); + visitAttributeEach(attrName, matchValue, matchFlag, depth); + }else{ + visitPreComposite(filterType, depth); + + AnyArray::iterator iter; + for(iter=values->begin(); iter!= values->end(); iter++){ + + if(iter != values->begin()){ + + visitInComposite(filterType, depth); + } + + AnyPtr matchValue = *iter; + visitAttributeEach(attrName, matchValue, matchFlag, depth); + } + + visitPostComposite(filterType, depth); + } + LogDebug(">>>"); + } + + void FolderQueryGenerator::visitAttributeEach(std::string& attrName, Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth){ + LogDebug("<<< attrName:[" << attrName << "], value:[" << value->toString() << "]"); + + if(matchFlag.compare(STRING_MATCH_EXACTLY) == 0){ + LogDebug("STRING_MATCH_EXACTLY"); + getMatchExactlyClause(attrName, value); + }else if(matchFlag.compare(STRING_MATCH_CONTAINS) == 0){ + LogDebug("STRING_MATCH_CONTAINS"); + getMatchContainsClause(attrName, value); + }else if(matchFlag.compare(STRING_MATCH_STARTSWITH) == 0){ + LogDebug("STRING_MATCH_STARTSWITH"); + getMatchStartsWithClause(attrName, value); + }else if(matchFlag.compare(STRING_MATCH_ENDSWITH) == 0){ + LogDebug("STRING_MATCH_ENDSWITH"); + getMatchEndsWithClause(attrName, value); + }else{ + LogDebug("[ERROR]invalid match flag[" << matchFlag << "]"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "invalid match flag:[" + matchFlag + "]"); + } + LogDebug(">>>"); + } + + void FolderQueryGenerator::visitAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth) { + LogDebug("<<< NOT IMPLEMENTED YET"); + } + + //TODO implement visitID + void FolderQueryGenerator::visitID(Api::Tizen::AnyArrayPtr &value, int depth) { + LogDebug("<<< NOT IMPLEMENTED YET"); + } + + int FolderQueryGenerator::getAccountId() + { + return m_accountId; + } + + std::string FolderQueryGenerator::getFolderPath() + { + return m_folderpath; + } + + bool FolderQueryGenerator::isFolderPathExist() + { + LogError("m_folderPathProcessing : " << m_folderPathProcessing); + return m_folderPathProcessing; + } + + void FolderQueryGenerator::reset(){ + m_folderPathProcessing = FALSE; + m_accountId = 0; + m_folderpath.clear(); + } + + + } + } //namespace Platform +} //namespace WrtPlugins diff --git a/src/platform/Tizen/Messaging/FolderQueryGenerator.h b/src/platform/Tizen/Messaging/FolderQueryGenerator.h new file mode 100644 index 0000000..7314e00 --- /dev/null +++ b/src/platform/Tizen/Messaging/FolderQueryGenerator.h @@ -0,0 +1,101 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * FolderQueryGenerator.h + * + * Created on: 2011. 10. 28. + * Author: sangtai + */ + +#ifndef FOLDERQUERYGENERATOR_H_ +#define FOLDERQUERYGENERATOR_H_ + +#include +#include + +#include + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + class FolderQueryGenerator: public TizenApis::Api::Tizen::IFilterVisitor{ + + public: + enum QueryGeneratorMode{ + MODE_EMAIL, + MODE_SMS_MMS + }; + + protected: + std::map attributeMap; + + private: + QueryGeneratorMode m_mode; + std::string m_query; + std::vector m_queryVector; + + int m_messageType; + + std::vector typeVector; + + std::string m_currentType; + + bool m_folderPathProcessing; + + int m_accountId; + std::string m_folderpath; + + static const std::string STRING_MATCH_EXACTLY; + static const std::string STRING_MATCH_CONTAINS; + static const std::string STRING_MATCH_STARTSWITH; + static const std::string STRING_MATCH_ENDSWITH; + static const std::string STRING_MATCH_CASESENSITIVE; + + static const int ACCOUNT_ID_NOT_INITIALIZED; + + public: + FolderQueryGenerator(); + virtual ~FolderQueryGenerator(); + + void visitPreComposite(Api::Tizen::FilterType& type, int depth); + void visitInComposite(Api::Tizen::FilterType& type, int depth); + void visitPostComposite(Api::Tizen::FilterType& type, int depth); + void visitAttribute(std::string& attrName, Api::Tizen::AnyArrayPtr& values, std::string& matchFlag, bool caseSensitive, int depth); + void visitAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth); + void visitID(Api::Tizen::AnyArrayPtr &value, int depth); + + int getAccountId(); + std::string getFolderPath(); + bool isFolderPathExist(); + void reset(); + + protected: + virtual bool getMatchExactlyClause(std::string& attrName, Api::Tizen::AnyPtr& value); + void visitAttributeEach(std::string& attrName, Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth); + + private: + std::string getMatchStartsWithClause(std::string& attrName, Api::Tizen::AnyPtr& value); + std::string getMatchEndsWithClause(std::string& attrName, Api::Tizen::AnyPtr& value); + std::string getMatchContainsClause(std::string& attrName, Api::Tizen::AnyPtr& value); + + }; + + typedef DPL::SharedPtr FolderQueryGeneratorPtr; + } // namespace Platform +} // namespace WrtPlugins +} +#endif diff --git a/src/platform/Tizen/Messaging/ISendingObserver.h b/src/platform/Tizen/Messaging/ISendingObserver.h new file mode 100755 index 0000000..62a9d1b --- /dev/null +++ b/src/platform/Tizen/Messaging/ISendingObserver.h @@ -0,0 +1,81 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file ISendingObserver.h + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef ISENDINGOBSERVER_H_ +#define ISENDINGOBSERVER_H_ + +#include "CallbackMgr.h" + +extern "C" { +#include +} + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +/* + * + */ +class ISendingObserver +{ + public: + ISendingObserver() : m_reqId(0) + { + } + + virtual ~ISendingObserver() + { + if (m_reqId) { + CallbackMgrSingleton::Instance().unregister(m_reqId); + } + } + + void setSendigRequestId(int id) + { + m_reqId = id; + } + + void setRecipient(const char* arg) + { + m_recipient = arg; + } + + std::string getRecipient() const + { + return m_recipient; + } + + virtual void sendingCallback(MSG_SENT_STATUS_S *sent_status) = 0; + + private: + int m_reqId; + std::string m_recipient; +}; +} +} +} +#endif /* ISENDINGOBSERVER_H_ */ diff --git a/src/platform/Tizen/Messaging/MailSender.cpp b/src/platform/Tizen/Messaging/MailSender.cpp new file mode 100755 index 0000000..e4132e8 --- /dev/null +++ b/src/platform/Tizen/Messaging/MailSender.cpp @@ -0,0 +1,322 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include "MailSender.h" +#include "NetworkStatus.h" +#include "Messaging.h" + +namespace { +const char* DBUS_FILTER_NETWORK_STATUS = + "type='signal',interface='User.Email.NetworkStatus'"; +} + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +MailSender& MailSender::getInstance() +{ + static MailSender instance; + return instance; +} + +int MailSender::send(const Api::Messaging::IEmailPtr& mail) +{ + Assert(mail && "Mail must not be NULL."); + + int mailId = mail->convertId(mail->getIdRef()); + LogDebug("send mailId = " << mailId); + SendRequestsIterator it = m_requests.find(mailId); + if (m_requests.end() != it) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Email: " << mailId << " already requested to be send."); + } + + return sendInternal(mail); +} + +void MailSender::cancel(int handle) +{ + SendRequestsIterator it = m_requests.find(handle); + if (m_requests.end() == it) { + //ThrowMsg(WrtDeviceApis::Commons::PlatformException, + // "Email handle : " << handle << " not found."); + LogDebug("Email handle" << handle << " not found!"); + return; + } + else + { + cancelInternal(it->second); + } +} + +// TODO Copied from former solution, refactor it. +void MailSender::OnEventReceived(const DBus::MessageEvent& event) +{ + LogDebug("HERE"); + NetworkStatusPtr msg(new NetworkStatus(event.GetArg0())); + int mailId = msg->getMailId(); + LogDebug("status : " << msg->getStatus() << " mailId : " << mailId); + int handle = 0; + + if ( msg->getStatus() == NOTI_SEND_FINISH || msg->getStatus() == NOTI_SEND_FAIL) + { + //find handle + SendRequestsIterator it = m_requests.begin(); + for (; it != m_requests.end() ; it++) + { + if ( it->second.mail->getUID() == mailId) + { + handle = it->first; + LogDebug("handle : " << handle); + break; + } + } + + if (msg->getStatus() == NOTI_SEND_FAIL) + { + LogDebug(" Error Code : " << msg->getErrorCode()); + } + } + else + { + if ( msg->getStatus() == NOTI_SEND_START ) + { + LogDebug("NOTI_SEND_START"); + } + else if ( msg->getStatus() == NOTI_SEND_CANCEL ) + { + LogDebug("NOTI_SEND_CANCEL"); + } + + return ; + } + + LogDebug("handle : " << handle); + + SendRequestsIterator it = m_requests.find(handle); //find reqeuset + if (m_requests.end() != it) { + switch (msg->getStatus()) { + case NOTI_SEND_START: + LogInfo("Start sending e-mail: " << mailId); + break; + + case NOTI_SEND_FINISH: + { + const Api::Messaging::IEmailPtr& mail = it->second.mail; + Api::Messaging::EventSendMessageReqReceiver* requestReceiver = + mail->getRequestReceiver(); + if (requestReceiver) { + Api::Messaging::EventSendMessagePtr event = mail->getSendMessageEvent(); + if (event) + { + for (size_t i = 0; i < mail->getToRecipients().getRecipientSize(); ++i) { + event->m_successRecipients.push_back(mail->getToRecipients().getRecipient(i)); + } + for (size_t i = 0; i < mail->getCcRecipients().getRecipientSize(); ++i) { + event->m_successRecipients.push_back(mail->getCcRecipients().getRecipient(i)); + } + for (size_t i = 0; i < mail->getBccRecipients().getRecipientSize(); ++i) { + event->m_successRecipients.push_back(mail->getBccRecipients().getRecipient(i)); + } + + requestReceiver->ManualAnswer(event); + } + + } + mail->setMessageStatus(Api::Messaging::MESSAGE_STATUS_SENT); + LogInfo("E-mail sent: " << mailId); + m_requests.erase(mailId); + break; + } + + case NOTI_SEND_FAIL: + { + const Api::Messaging::IEmailPtr& mail = it->second.mail; + Api::Messaging::EventOnSendingFailedEmitterPtr emitter = mail->getEmitter(); + Api::Messaging::EventSendMessageReqReceiver *requestReceiver = + mail->getRequestReceiver(); + if (emitter) { + Api::Messaging::EventOnSendingFailedPtr event( + new Api::Messaging::EventOnSendingFailed() + ); + switch (msg->getErrorCode()) { + case EMF_ERROR_NO_SIM_INSERTED: + case EMF_ERROR_FLIGHT_MODE: + event->setError( + Api::Messaging::EventOnSendingFailed::NO_NETWORKING + ); + break; + + case EMF_ERROR_SMTP_SEND_FAILURE: + case EMF_ERROR_NO_SUCH_HOST: + case EMF_ERROR_CONNECTION_FAILURE: + case EMF_ERROR_CONNECTION_BROKEN: + case EMF_ERROR_INVALID_SERVER: + case EMF_ERROR_NO_RESPONSE: + event->setError( + Api::Messaging::EventOnSendingFailed::NO_CONNECTION + ); + break; + + default: + event->setError(Api::Messaging::EventOnSendingFailed::UNKNOWN); + } + emitter->emit(event); + } else if (requestReceiver) { + Api::Messaging::EventSendMessagePtr event = mail->getSendMessageEvent(); + event->setExceptionCode( + WrtDeviceApis::Commons::ExceptionCodes::UnknownException + ); + requestReceiver->ManualAnswer(event); + } + mail->setMessageStatus(Api::Messaging::MESSAGE_STATUS_FAILED); + + LogInfo("Sending e-mail: " << mailId << + " failed with error: " << msg->getErrorCode()); + m_requests.erase(mailId); + break; + } + } + } +} + +MailSender::MailSender() : + m_dbusThread(new DPL::Thread()), + m_dbus(new DBus::Connection()) +{ + m_dbusThread->Run(); + + m_dbus->setWorkerThread(m_dbusThread.Get()); + m_dbus->AddListener(this); + m_dbus->SwitchAllListenersToThread( + ThreadPool::getInstance().getThreadRef(ThreadEnum::MESSAGING_THREAD) + ); + m_dbus->addFilter(DBUS_FILTER_NETWORK_STATUS); + m_dbus->open(DBUS_BUS_SYSTEM); + + //start email service + if (EMF_ERROR_NONE == email_service_begin()) { + LogDebug("Email service Begin\n"); + if (EMF_ERROR_NONE == email_open_db()) { + LogDebug("Email open DB success\n"); + } + else{ + LogDebug("Email open DB failed\n"); + } + } + else{ + LogDebug("Email service not started\n"); + } + +} + +MailSender::~MailSender() +{ + m_dbus->RemoveListener(this); + m_dbus->close(); + + m_dbusThread->Quit(); + + + //close email service + if (EMF_ERROR_NONE == email_close_db()) { + LogDebug("Email Close DB Success\n"); + if (EMF_ERROR_NONE == email_service_end()){ + LogDebug("Email service close Success\n"); + } + else{ + LogDebug("Email service end failed\n"); + } + } + else{ + LogDebug("Email Close DB failed\n"); + } + +} + +int MailSender::sendInternal(const Api::Messaging::IEmailPtr& mail) +{ + int mailId = mail->convertId(mail->getIdRef()); + + emf_mailbox_t mailbox = {}; + mailbox.account_id = + Messaging::getInstance().getEmailAccountId(mail->getFromRef()); + // TODO Causes warning during compilation, refactor it. + mailbox.name = (char*)EMF_SENTBOX_NAME; + + emf_option_t options = {}; + options.keep_local_copy = 1; + unsigned int emf_handle=0; + + int error = email_send_mail(&mailbox, + mailId, + &options, + &emf_handle); + + if (EMF_ERROR_NONE != error) { + LogDebug("Send Fail error = " << error ); + m_requests.erase(mailId); + mail->setMessageStatus(Api::Messaging::MESSAGE_STATUS_SENDING); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Failed to initialize send request. [" << error << "]"); + return -1; + } + else + { + m_requests.insert(std::make_pair(emf_handle, SendRequestData(emf_handle, mail))); + } + + LogDebug("emf Handle : " << emf_handle +<< "requests size :" << m_requests.size() ); + + return emf_handle; +} + +void MailSender::cancelInternal(const SendRequestData& data) +{ + int error = email_cancel_job(data.mail->getAccountID(), data.handle); + if (EMF_ERROR_NONE != error) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Couldn't cancel sending for email: " << + data.mail->getIdRef()); + } + + m_requests.erase(data.handle); +} +} +} +} diff --git a/src/platform/Tizen/Messaging/MailSender.h b/src/platform/Tizen/Messaging/MailSender.h new file mode 100755 index 0000000..48c6ece --- /dev/null +++ b/src/platform/Tizen/Messaging/MailSender.h @@ -0,0 +1,85 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef MAILSENDER_H_ +#define MAILSENDER_H_ + +#include +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +// TODO Not thread-safe, make it. +class MailSender : private DPL::EventListener +{ + public: + static MailSender& getInstance(); + + public: + int send(const Api::Messaging::IEmailPtr& mail); + void cancel(int handle); + + protected: + void OnEventReceived(const DBus::MessageEvent& event); + + private: + struct SendRequestData + { + unsigned int handle; + Api::Messaging::IEmailPtr mail; + + explicit SendRequestData(const Api::Messaging::IEmailPtr& mail) : + handle(0), + mail(mail) + { + } + explicit SendRequestData(const int handle, const Api::Messaging::IEmailPtr& mail) : + handle(handle), + mail(mail) + { + } + }; + + typedef std::map SendRequests; + typedef SendRequests::iterator SendRequestsIterator; + + private: + MailSender(); + ~MailSender(); + + int sendInternal(const Api::Messaging::IEmailPtr& data); + void cancelInternal(const SendRequestData& data); + + private: + DPL::ScopedPtr m_dbusThread; + DBus::ConnectionPtr m_dbus; + SendRequests m_requests; +}; +} +} +} +#endif // MAILSENDER_H_ diff --git a/src/platform/Tizen/Messaging/MailSync.cpp b/src/platform/Tizen/Messaging/MailSync.cpp new file mode 100755 index 0000000..2050442 --- /dev/null +++ b/src/platform/Tizen/Messaging/MailSync.cpp @@ -0,0 +1,657 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +#include +#endif + +#include "MailSync.h" +#include "SyncNetworkStatus.h" +#include +//for vconf +#include +#include + +namespace { +const char* DBUS_FILTER_NETWORK_STATUS = + "type='signal',interface='User.Email.NetworkStatus'"; +//const char* DBUS_FILTER_EMAIL_RECEIVED = +// "type='signal',interface='User.Email.StorageChange'"; +} + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +MailSync& MailSync::getInstance() +{ + static MailSync instance; + return instance; +} + +MailSync::MailSync() : + m_dbusThread(new DPL::Thread()), + m_dbus(new DBus::Connection()) +{ + m_dbusThread->Run(); + + m_dbus->setWorkerThread(m_dbusThread.Get()); + m_dbus->AddListener(this); + m_dbus->SwitchAllListenersToThread( + ThreadPool::getInstance().getThreadRef(ThreadEnum::MESSAGING_THREAD) + ); + m_dbus->addFilter(DBUS_FILTER_NETWORK_STATUS); + m_dbus->open(DBUS_BUS_SYSTEM); + + //start email service + if (EMF_ERROR_NONE == email_service_begin()) { + LogDebug("Email service Begin\n"); + if (EMF_ERROR_NONE == email_open_db()) { + LogDebug("Email open DB success\n"); + } + else{ + LogDebug("Email open DB failed\n"); + } + } + else{ + LogDebug("Email service not started\n"); + } + + //get retriving count + int slot_size = -1; + vconf_get_int("db/email/slot_size", &(slot_size)); + if ( slot_size > 0 ) + m_default_slot_size = slot_size; + + LogDebug( "Slot Size : " << m_default_slot_size ); + +} + +MailSync::~MailSync() +{ + m_dbus->RemoveListener(this); + m_dbus->close(); + + m_dbusThread->Quit(); + + //close email service + if (EMF_ERROR_NONE == email_close_db()) { + LogDebug("Email Close DB Success\n"); + if (EMF_ERROR_NONE == email_service_end()) + { + LogDebug("Email service close Success\n"); + } + else + { + LogDebug("Email service end failed\n"); + } + } + else{ + LogDebug("Email Close DB failed\n"); +} +} + +int MailSync::downloadBody( const Api::Messaging::IEmailPtr& mail ) +{ + if ( mail ) + { + int mailId = mail->convertId(mail->getIdRef()); // get mail id + LogDebug("start attachment, mail Id : " << mail->getIdRef()); + SyncRequestIterator it; + for( it = m_SyncRequests.begin(); it != m_SyncRequests.end(); ++it) + { + const Api::Messaging::IEmailPtr& email = it->second.mail; + LogDebug ( "Requests mail ID:" << mail->convertId(email->getIdRef()) ); + if ( mailId == mail->convertId(email->getIdRef())) + { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "download Body: " << mailId << " already requested to be download Body."); + } + } + } + + return downloadBodyInternal(mail, mail->getAccountID()); + +} + +void MailSync::cancelDownloadBody(int handle) +{ + Assert(handle > -1); + + SyncRequestIterator it = m_SyncRequests.find(handle); + if ( m_SyncRequests.end() != it) + { + if ( it->second.messagingService ) + cancelEmailJobInternal( it->second.messagingService->getAccountID() , it->second.handle); + //cancelDownloadBodyInternal(it->second.mail, it->second.handle ); + } + else + { + LogDebug("Don't find cancel DownloadBody handle : " << handle); + //ThrowMsg(WrtDeviceApis::Commons::NotFoundException, "Email: " << mailId << " not found."); + } + +} + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +void MailSync::downloadAttachment(const Api::Messaging::IEmailPtr& mail, const Api::Messaging::IAttachmentPtr& attachment) +{ + if ( mail && attachment ) + { + int mailId = mail->convertId(mail->getIdRef()); // get mail id + LogDebug("start attachment, mail Id : " << mail->getIdRef()); + SyncRequestIterator it; + for( it = m_SyncRequests.begin(); it != m_SyncRequests.end(); ++it) + { + const Api::Messaging::IAttachmentPtr& iattachment = it->second.attachment; + LogDebug ( "Requests Attachment ID:" << iattachment->getAttachmentID() << " Input Attachment ID: " << attachment->getAttachmentID()); + if (iattachment->getAttachmentID() == attachment->getAttachmentID()) + { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Attachment: " << attachment->getAttachmentID() << " already requested to be download Attachment."); + } + } + } + downloadAttachmentInternal(mail, mail->getAccountID(), attachment); + +} +#endif + +int MailSync::syncAccount(const Api::Messaging::IMessagingServicePtr& messagingService, const int limit) +{ + LogDebug("syncAccount : " << limit); + if (messagingService) + { + int accountId = messagingService->getAccountID(); + LogDebug("start sync, account Id : " << accountId); + SyncRequestIterator it; + for( it = m_SyncRequests.begin(); it != m_SyncRequests.end(); ++it) + { + const Api::Messaging::IMessagingServicePtr& messagingService = it->second.messagingService; + if (messagingService && messagingService->getAccountID() == accountId) + { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Sync: " << accountId << " already requested to be Sync Account."); + } + } + return syncAccountInternal(messagingService, limit); + } + else + { + LogDebug("messagingService is NULL"); + } + + LogDebug("end sync" ); + return -1; +} + +int MailSync::syncAccountInternal( const Api::Messaging::IMessagingServicePtr& messagingService, const int limit) +{ + LogDebug("syncAccountInternal limit: " << limit); + + int account_id = messagingService->getAccountID(); + int err = 0; + emf_mailbox_t mailbox ; + unsigned emf_handle = 0; + + memset(&mailbox, 0, sizeof(emf_mailbox_t)); + mailbox.name = NULL; /* all folders. */ + mailbox.account_id = account_id; //set account id. + int slot_size; + + if ( limit < 0 ) + slot_size = m_default_slot_size; + else + slot_size = limit; + + email_set_mail_slot_size(0, NULL, slot_size); + + LogDebug("mailbox.account_id " << mailbox.account_id ); + err = email_sync_header(&mailbox, &emf_handle); + LogDebug("emf_handle " << emf_handle); + + if (err != EMF_ERROR_NONE) { + LogDebug("fail to sync all folders - err : " << err); + } + else + { + LogDebug("Insert sync request"); + SyncRequestData data = SyncRequestData(emf_handle, MESSAGING_SERVICE_SYNC_TYPE_SYNC, messagingService); + m_SyncRequests.insert(std::make_pair(emf_handle, data)); + } + + return emf_handle; +} + +void MailSync::syncAccountCancel(const int handle) +{ + LogDebug("sync cancel"); + Assert(handle > -1); + + SyncRequestIterator it = m_SyncRequests.find(handle); + if ( m_SyncRequests.end() != it) + { + if ( it->second.messagingService ) + cancelEmailJobInternal( it->second.messagingService->getAccountID() , it->second.handle); + } + else + { + LogDebug("Don't find cancel Sync handle : " << handle); + //ThrowMsg(WrtDeviceApis::Commons::NotFoundException, "Email: " << mailId << " not found."); + } +} + +int MailSync::syncFolder(const Api::Messaging::IMessagingServicePtr& messagingService, const std::string& folderName, const int limit) +{ + LogDebug("sync folder : " << folderName << " limit : " << limit); + + if (messagingService) + { + int accountId = messagingService->getAccountID(); + LogDebug("start sync, account Id : " << accountId); + SyncRequestIterator it; + for( it = m_SyncRequests.begin(); it != m_SyncRequests.end(); ++it) + { + const Api::Messaging::IMessagingServicePtr& messagingService = it->second.messagingService; + if (messagingService && messagingService->getAccountID() == accountId + && it->second.folderName == folderName) + { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Sync: " << accountId << " already requested to be Sync Account."); + } + } + + return syncFolderInternal(messagingService, folderName, limit); + } + else + { + LogDebug("messagingService is NULL"); + } + + return -1; + +} + +void MailSync::syncFolderCancel(const int handle) +{ + LogDebug("sync Folder Cancel"); + Assert(handle > -1); + + SyncRequestIterator it = m_SyncRequests.find(handle); + if ( m_SyncRequests.end() != it) + { + if ( it->second.messagingService ) + cancelEmailJobInternal( it->second.messagingService->getAccountID() , it->second.handle); + } + else + { + LogDebug("Don't find cancel Sync Folder handle : " << handle); + //ThrowMsg(WrtDeviceApis::Commons::NotFoundException, "Email: " << mailId << " not found."); + } +} + +int MailSync::syncFolderInternal(const Api::Messaging::IMessagingServicePtr& messagingService, const std::string& folderName, const int limit) +{ + LogDebug("Folder Name=" << folderName << " limit : " << limit); + + int account_id = messagingService->getAccountID(); + emf_mailbox_t mailbox; + gchar *src_box =g_strdup( folderName.c_str() ); + unsigned emf_handle = 0; + + int err = 0; + memset(&mailbox, 0, sizeof(emf_mailbox_t)); + mailbox.name = src_box; + mailbox.account_id = account_id; + int slot_size = 0; + + if ( limit < 0 ) + slot_size = m_default_slot_size; + else + slot_size = limit; + + email_set_mail_slot_size(0, src_box, slot_size); + + err = email_sync_header(&mailbox, &emf_handle); + if (err != EMF_ERROR_NONE) { + LogDebug("fail to sync folders - err : " << err); + } + else + { + LogDebug("Insert sync request"); + + SyncRequestData data = SyncRequestData(emf_handle, MESSAGING_SERVICE_SYNC_TYPE_SYNC_FOLDER, messagingService, folderName); + m_SyncRequests.insert(std::make_pair(emf_handle, data)); + } + + if (src_box) { + g_free(src_box); + } + + return emf_handle; +} + + +// TODO Copied from former solution, refactor it. +void MailSync::OnEventReceived(const DBus::MessageEvent& event) +{ + LogDebug("OnEventReceived"); + SyncNetworkStatusPtr syncNetworkStatus(new SyncNetworkStatus(event.GetArg0())); +// int mailId = syncNetworkStatus->getMailId(); //if email body download mode. + int status = syncNetworkStatus->getStatus(); + int handle = syncNetworkStatus->getHandle(); + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + // if Attachment Load + if ( status == NOTI_DOWNLOAD_ATTACH_FINISH || + status == NOTI_DOWNLOAD_ATTACH_FAIL ) + { + int nth = handle; + LogDebug(" Debus mailID = " << mailId << " , Nth = " << nth ); + + SyncRequestIterator it = m_SyncRequests.begin(); + for ( it; it != m_SyncRequests.end(); it++ ) + { + const Api::Messaging::IEmailPtr& mail = it->second.mail; + + LogDebug(" request mailID = " << mail->getUID() << " , Nth = " << (it->second.attachment)->getNth() ); + if ( mail->getUID() == mailId && nth == (it->second.attachment)->getNth()) + { + Api::Messaging::EventMessagingServiceReqReceiver* requestReceiver = mail->getRequestReceiver(); + if ( mail && requestReceiver ) + { + Api::Messaging::EventMessagingServicePtr event = mail->getMessagingServiceEvent(); + + if (status == NOTI_DOWNLOAD_ATTACH_FINISH) + { + LogDebug(" Attachment Finish " ); + int acountId = mail->getAccountID(); + const Api::Messaging::IAttachmentPtr& attachment = it->second.attachment; + if (attachment) + { + emf_mailbox_t mailbox ; + emf_attachment_info_t *attach_info = NULL; + memset(&mailbox, 0, sizeof(emf_mailbox_t)); + mailbox.account_id = acountId; //set account id. + int attachmentId = attachment->getAttachmentID(); + std::stringstream stream; + stream << attachment->getAttachmentID(); + LogDebug("Attachment ID = " << stream.str()); + + int err = email_get_attachment_info( &mailbox, mail->getUID(), stream.str().c_str() , &attach_info ); + if (err == EMF_ERROR_NONE) { + LogDebug("attachment Name : " << attach_info->name); + LogDebug("attachment ID : " << attach_info->attachment_id); + attachment->init(attach_info->savename, false); + } + else + { + LogDebug("fail to email_get_attachment_info - err : " << err); + } + + } + + } + else + { + event->setExceptionCode( WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + LogDebug(" Attachment Failed " ); + } + + requestReceiver->ManualAnswer(event); + m_SyncRequests.erase( handle ); + + } + + break; + } + } + } + else if ( status == NOTI_DOWNLOAD_ATTACH_START ) + { + LogDebug("DownLoading... attachment : size = " << syncNetworkStatus->getErrorCode()); + return; + } +#endif + + SyncRequestIterator it = m_SyncRequests.find(handle); + if ( m_SyncRequests.end() != it) + { + int syncType = it->second.syncType; + LogDebug(" Sync ... handle : " << handle << " status : " << status << " SyncType: " << syncType); + + switch(syncType) + { + case MESSAGING_SERVICE_SYNC_TYPE_SYNC: + { + LogDebug(" Sync Account"); + const Api::Messaging::IMessagingServicePtr& messagingService = it->second.messagingService; + Api::Messaging::EventMessagingServiceReqReceiver* requestReceiver = messagingService->getRequestReceiver(); + + if ( messagingService && requestReceiver) + { + Api::Messaging::EventMessagingServicePtr event = messagingService->getMessagingServiceEvent(); + if ( status == NOTI_DOWNLOAD_FINISH ) + { + LogDebug("Sync Success"); + requestReceiver->ManualAnswer(event); + m_SyncRequests.erase( handle ); + } + else if ( status == NOTI_DOWNLOAD_FAIL ) + { + LogDebug("Sync Fail"); + event->setExceptionCode( WrtDeviceApis::Commons::ExceptionCodes::UnknownException ); + requestReceiver->ManualAnswer(event); + m_SyncRequests.erase( handle ); + } + } + else + { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "request Receiver is NULL. "); + } + + break; + } + case MESSAGING_SERVICE_SYNC_TYPE_SYNC_FOLDER: + { + LogDebug("Sync Folder"); + const Api::Messaging::IMessagingServicePtr& messagingService = it->second.messagingService; + Api::Messaging::EventMessagingServiceReqReceiver* requestReceiver = messagingService->getRequestReceiver(); + + if ( messagingService && requestReceiver) + { + Api::Messaging::EventMessagingServicePtr event = messagingService->getMessagingServiceEvent(); + if ( status == NOTI_DOWNLOAD_FINISH ) + { + LogDebug("Sync Success"); + requestReceiver->ManualAnswer(event); + m_SyncRequests.erase( handle ); + } + else if ( status == NOTI_DOWNLOAD_FAIL ) + { + LogDebug("Sync Fail"); + event->setExceptionCode( WrtDeviceApis::Commons::ExceptionCodes::UnknownException ); + requestReceiver->ManualAnswer(event); + m_SyncRequests.erase( handle ); + } + } + else + { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "request Receiver is NULL. "); + } + break; + } + case MESSAGING_SERVICE_SYNC_TYPE_DOWNLOAD_BODY: + { + LogDebug(" DownLoad Body"); + const Api::Messaging::IEmailPtr& mail = it->second.mail; // IEmailPtr + Api::Messaging::EventMessagingServiceReqReceiver* requestReceiver = mail->getRequestReceiver(); + if (mail && requestReceiver) { + Api::Messaging::EventMessagingServicePtr event = mail->getMessagingServiceEvent(); + if ( status == NOTI_DOWNLOAD_BODY_FINISH ) + { + requestReceiver->ManualAnswer(event); + m_SyncRequests.erase( handle ); + } + else if ( status == NOTI_DOWNLOAD_BODY_FAIL ) + { + event->setExceptionCode( WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + requestReceiver->ManualAnswer(event); + m_SyncRequests.erase( handle ); + } + } + else + { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "request Receiver is NULL. "); + } + + break; + } + + } + + + } + +} + +int MailSync::downloadBodyInternal( const Api::Messaging::IEmailPtr& mail, int account_id) +{ + + LogDebug("downloadInternal"); + + int err = 0; + int mailId = mail->convertId(mail->getIdRef()); + unsigned int emf_handle = 0; + + emf_mailbox_t mailbox; + memset(&mailbox, 0, sizeof(emf_mailbox_t)); + mailbox.account_id = account_id; //set account id. + LogDebug("mailbox.account_id " << mailbox.account_id ); + err = email_download_body(&mailbox, mailId,0, &emf_handle); + + if (err != EMF_ERROR_NONE) { + LogDebug("fail to downloadBody - err : " << err); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Failed to initialize downloadBody request. [" << err << "]"); + } + else + { + LogDebug("Insert downloadBody request"); + LogDebug("handle : " << emf_handle); + SyncRequestData data = SyncRequestData(emf_handle, MESSAGING_SERVICE_SYNC_TYPE_DOWNLOAD_BODY, mail); + m_SyncRequests.insert(std::make_pair(emf_handle, data)); + } + + return emf_handle; + +} + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +void MailSync::downloadAttachmentInternal(const Api::Messaging::IEmailPtr& mail, int account_id, const Api::Messaging::IAttachmentPtr& attachment) +{ + LogDebug("downloadAttachmentInternal"); + + int err = 0; + int nth = 0; + int idx = 0; + int mailId = mail->convertId(mail->getIdRef()); + unsigned emf_handle = 0; + + emf_mailbox_t mailbox; + //gchar *src_box = g_strdup(folder_name); + memset(&mailbox, 0, sizeof(emf_mailbox_t)); + mailbox.account_id = account_id; //set account id. + LogDebug("mailbox.account_id " << mailbox.account_id ); + LogDebug("Attachment ID :" << attachment->getAttachmentID()); + + std::stringstream stream; + //stream << attachment->getAttachmentID(); + + if (stream.fail()) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Couldn't convert e-mail attachment id"); + } + + //get nth + std::vector attachments = mail->getAttachments(); + for ( int i = 0 ; i < attachments.size() ; i ++) + { + LogDebug( "attachment ID is = " << attachments[i]->getAttachmentID()); + if (attachments[i]->getAttachmentID() == attachment->getAttachmentID()) + { + nth = i; + break; + } + } + + stream << nth+1; + LogDebug("nth = " << stream.str()); + + LogDebug("attachment Order Index = " << stream.str()); + err = email_download_attachment(&mailbox, mailId, stream.str().c_str() , &emf_handle); + if (err != EMF_ERROR_NONE) { + LogDebug("fail to downloadAttachment - err : " << err); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Failed to initialize downloadAttachment request. [" << err << "]"); + } + else + { + LogDebug("Insert downloadAttachment request"); + LogDebug("handle : " << emf_handle); + SyncRequestData data = SyncRequestData( emf_handle, + MESSAGING_SERVICE_SYNC_TYPE_DOWNLOAD_ATTACHMENT, mail, attachment ); + m_SyncRequests.insert(std::make_pair(emf_handle, data)); + } + +} +#endif + +void MailSync::cancelEmailJobInternal(int accountId, int handle) +{ + LogDebug("cancel Email Job, account : " < +#include +#include +#include +#include +#include +#include +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +#include +#endif +#include +#include + + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +enum MessagingServiceSyncType +{ + MESSAGING_SERVICE_SYNC_TYPE_DOWNLOAD_BODY = 1, + MESSAGING_SERVICE_SYNC_TYPE_DOWNLOAD_ATTACHMENT, + MESSAGING_SERVICE_SYNC_TYPE_SYNC, + MESSAGING_SERVICE_SYNC_TYPE_SYNC_FOLDER, + MESSAGING_SERVICE_SYNC_TYPE_COUNT, +}; + +class MailSync : private DPL::EventListener +{ + public : + static MailSync& getInstance(); + + public : + int downloadBody(const Api::Messaging::IEmailPtr& mail); //downloadBody + void cancelDownloadBody(int handle); +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + void downloadAttachment(const Api::Messaging::IEmailPtr& mail, const Api::Messaging::IAttachmentPtr& attachment); + void cancelDownloadAttachment(int AttachmentId ); +#endif + int syncAccount(const Api::Messaging::IMessagingServicePtr& messagingService, const int limit); + void syncAccountCancel(const int handle); + int syncFolder(const Api::Messaging::IMessagingServicePtr& messagingService, const std::string& folderName, const int limit); + void syncFolderCancel(const int handle); + + protected: + void OnEventReceived(const DBus::MessageEvent& event); + + private: + + struct SyncBodyDownloadRequestData + { + unsigned int handle; + Api::Messaging::IEmailPtr mail; //mail + + explicit SyncBodyDownloadRequestData(const Api::Messaging::IEmailPtr& mail) : + handle(0), + mail(mail) + { + } + }; + + struct SyncRequestData + { + unsigned int handle; + int syncType; + Api::Messaging::IEmailPtr mail; //mail +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + Api::Messaging::IAttachmentPtr attachment; //attachment +#endif + Api::Messaging::IMessagingServicePtr messagingService; //MessagingService + std::string folderName; //Folder + //Type + + explicit SyncRequestData ( + unsigned int handle, + int syncType, + const Api::Messaging::IEmailPtr& mail, +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + const Api::Messaging::IAttachmentPtr& attachment, +#endif + const Api::Messaging::IMessagingServicePtr& messagingService, + std::string& folderName) : + handle(handle), + syncType(syncType), + mail(mail), +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + attachment(attachment), +#endif + messagingService(messagingService), + folderName(folderName) + { + } + + explicit SyncRequestData ( + unsigned int handle, + int syncType, + const Api::Messaging::IMessagingServicePtr& messagingService) : + handle(handle), + syncType(syncType), + messagingService(messagingService) + { + } + + explicit SyncRequestData ( + unsigned int handle, + int syncType, + const Api::Messaging::IMessagingServicePtr& messagingService, + const std::string& folderName + ) : + handle(handle), + syncType(syncType), + messagingService(messagingService), + folderName(folderName) + { + } + + explicit SyncRequestData ( + unsigned int handle, + int syncType, + const Api::Messaging::IEmailPtr& mail) : + handle(handle), + syncType(syncType), + mail(mail) + { + } +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + explicit SyncRequestData ( + unsigned int handel, + int syncType, + const Api::Messaging::IEmailPtr& mail, + const Api::Messaging::IAttachmentPtr& attachment + ) : + handle(handle), + syncType(syncType), + mail(mail), + attachment(attachment) + { + } +#endif + }; + + typedef std::map SyncRequests; + typedef SyncRequests::iterator SyncRequestIterator; + + private: + MailSync(); + ~MailSync(); + + int syncAccountInternal(const Api::Messaging::IMessagingServicePtr& messagingService, const int limit); + int syncFolderInternal(const Api::Messaging::IMessagingServicePtr& messagingService, const std::string& folderName, const int limit); + int downloadBodyInternal( const Api::Messaging::IEmailPtr& mail, int account_id ); + + void cancelEmailJobInternal(int accountId, int handle); + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + void downloadAttachmentInternal(const Api::Messaging::IEmailPtr& mail, int account_id, const Api::Messaging::IAttachmentPtr& attachment ); + void cancelDownloadAttachmentInternal( const SyncAttachmentDownloadRequests& data ); +#endif + private: + DPL::ScopedPtr m_dbusThread; + DBus::ConnectionPtr m_dbus; + + SyncRequests m_SyncRequests; + int m_default_slot_size; //slot size +}; + +} +} +} + +#endif //MAILSYNC_H_ diff --git a/src/platform/Tizen/Messaging/MessageFolder.cpp b/src/platform/Tizen/Messaging/MessageFolder.cpp new file mode 100755 index 0000000..63e53ef --- /dev/null +++ b/src/platform/Tizen/Messaging/MessageFolder.cpp @@ -0,0 +1,141 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** +* @file EmailFolder.cpp +* @author Oy Kwon (sirot.kwon@samsung.com) +* @version 0.1 +*/ + + +#include "MessageFolder.h" +#include +#include +#include "MsgServiceHandleMgr.h" +#include + +extern "C" { +#include +#include +#include +#include +#include +} + +using namespace DPL; + +namespace TizenApis { +namespace Platform { +namespace Messaging { + + +MessageFolder::MessageFolder() +{ +} + +MessageFolder::MessageFolder(emf_mailbox_t m_mailboxes) +{ + m_id = (int)m_mailboxes.mailbox_type; + m_parentid = -1; + m_accountid = m_mailboxes.account_id; + m_contentType = TYPE_EMAIL; + m_name = m_mailboxes.alias; + m_path = m_mailboxes.name; + m_type = getFolderType(m_mailboxes.mailbox_type); + m_synchronizable = m_mailboxes.synchronous; + +} + +MessageFolder::~MessageFolder() +{ +} + +void MessageFolder::setName(std::string name) +{ + m_name = name; +} +void MessageFolder::setSynchronizable(bool synchronizable) +{ + m_synchronizable = synchronizable; +} + + +// getter +unsigned long MessageFolder::getId() +{ + return m_id; +} +unsigned long MessageFolder::getParentId() +{ + return m_parentid; +} +unsigned long MessageFolder::getAccountId() +{ + return m_accountid; +} +unsigned short MessageFolder::getContentType() +{ + return m_contentType; +} +std::string MessageFolder::getName() +{ + return m_name; +} +std::string MessageFolder::getPath() +{ + return m_path; +} +unsigned short MessageFolder::getType() +{ + return m_type; +} + +bool MessageFolder::getSynchronizable() +{ + return m_synchronizable; +} + +int MessageFolder::getFolderType(emf_mailbox_type_e folderType) +{ + if(EMF_MAILBOX_TYPE_INBOX == folderType) + { + return FOLDER_INBOX; + } + else if(EMF_MAILBOX_TYPE_OUTBOX == folderType) + { + return FOLDER_OUTBOX; + } + else if(EMF_MAILBOX_TYPE_DRAFT == folderType) + { + return FOLDER_DRAFTS; + } + else if(EMF_MAILBOX_TYPE_SENTBOX == folderType) + { + return FOLDER_SENTBOX; + } + else if(EMF_MAILBOX_TYPE_ALL_EMAILS != folderType) + { + return FOLDER_NOTSTANDARD; + } + + return FOLDER_NOTSTANDARD; +} + + +} +} +} + diff --git a/src/platform/Tizen/Messaging/MessageFolder.h b/src/platform/Tizen/Messaging/MessageFolder.h new file mode 100755 index 0000000..7a645fd --- /dev/null +++ b/src/platform/Tizen/Messaging/MessageFolder.h @@ -0,0 +1,95 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + /** + * @file MessageFolder.h + * @author Oy Kwon (sirot.kwon@samsung.com) + * @version 0.1 + */ + +#ifndef MESSAGEFOLDER_H +#define MESSAGEFOLDER_H + +#include +#include +#include +#include +#include + +#include + + +namespace TizenApis { +namespace Platform { +namespace Messaging { + + +class MessageFolder : public Api::Messaging::IMessageFolder +{ +public: + + typedef enum + { + FOLDER_INBOX = 1, + FOLDER_OUTBOX = 2, + FOLDER_DRAFTS = 3, + FOLDER_SENTBOX = 4, + FOLDER_NOTSTANDARD = 7, + } MsgFolder_FolerType; + + typedef enum + { + TYPE_SMS = 1, + TYPE_MMS = 2, + TYPE_EMAIL = 3, + TYPE_CHAT = 4, + } MsgFolder_ContentType; + + MessageFolder(); + MessageFolder(emf_mailbox_t m_mailboxes); + ~MessageFolder(); + + void setName(std::string name); + void setSynchronizable(bool synchronizable); + + unsigned long getId(); + unsigned long getParentId(); + unsigned long getAccountId(); + unsigned short getContentType(); + std::string getName(); + std::string getPath(); + unsigned short getType(); + bool getSynchronizable(); + int getFolderType(emf_mailbox_type_e folderType); +// int convertFolderId(const string& arg) const; + +private: + unsigned long m_id; + unsigned long m_parentid; + unsigned long m_accountid; + unsigned short m_contentType; + std::string m_name; + std::string m_path; + unsigned short m_type; + bool m_synchronizable; + +}; +} +} +} + +#endif + diff --git a/src/platform/Tizen/Messaging/MessageQueryGenerator.cpp b/src/platform/Tizen/Messaging/MessageQueryGenerator.cpp new file mode 100755 index 0000000..39cbb73 --- /dev/null +++ b/src/platform/Tizen/Messaging/MessageQueryGenerator.cpp @@ -0,0 +1,721 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * MessageQueryGenerator.cpp + * + * Created on: 2011. 10. 28. + * Author: sangtai + */ + +#include "MessageQueryGenerator.h" +#include "API/Messaging/MessageFilterValidatorFactory.h" +#include "API/Messaging/ConversationFilterValidatorFactory.h" + +#include +#include +#include + +#include + +#include + +using namespace std; +using namespace TizenApis::Api::Tizen; + +namespace TizenApis { + + namespace Platform { + namespace Messaging { + + const std::string MessageQueryGenerator::STRING_MATCH_EXCACTLY = "EXACTLY"; + const std::string MessageQueryGenerator::STRING_MATCH_CONTAINS = "CONTAINS"; + const std::string MessageQueryGenerator::STRING_MATCH_STARTSWITH = "STARTSWITH"; + const std::string MessageQueryGenerator::STRING_MATCH_ENDSWITH = "ENDSWITH"; +// const std::string MessageQueryGenerator::STRING_MATCH_CASESENSITIVE = "CASESENSITIVE"; + + const std::string MessageQueryGenerator::STRING_WHERE = "WHERE "; + const std::string MessageQueryGenerator::STRING_SUFFIX = ""; + const std::string MessageQueryGenerator::STRING_DIRECTION = "A.MSG_DIRECTION"; + + const int MessageQueryGenerator::MESSAGE_TYPE_NOT_INITIALIZED = -1; + + MessageQueryGenerator::MessageQueryGenerator():m_messageType(MESSAGE_TYPE_NOT_INITIALIZED) { + m_query.append(getQueryPrefix()); + + m_limit = 0; + m_offset = 0; + m_mode = MODE_EMAIL; + + initAttributeMap(); + } + + MessageQueryGenerator::MessageQueryGenerator(const Api::Tizen::SortModePtr& sortMode, const long limit, const long offset): + m_messageType(MESSAGE_TYPE_NOT_INITIALIZED){ + LogDebug("<<< limit:" << limit << ", offset:" << offset); + + m_query.append(getQueryPrefix()); + + //TODO check sort mode validation + m_sortMode = sortMode; + + m_limit = limit; + m_offset = offset; + m_mode = MODE_EMAIL; + + initAttributeMap(); + } + + MessageQueryGenerator::~MessageQueryGenerator() { + } + + void MessageQueryGenerator::reset(QueryGeneratorMode mode){ + m_query.clear(); + m_queryVector.clear(); + + m_limit = 0; + m_offset = 0; + m_mode = mode; + + m_query.append(getQueryPrefix()); + + initAttributeMap(); + } + + void MessageQueryGenerator::setEmailAttributeMap(){ + attributeMap.clear(); + + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_ID, "mail_id")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_FOLDER, "mailbox_type")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_TIMESTAMP, "date_time")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_FROM, "full_address_from")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_TO, "full_address_to")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_CC, "full_address_cc")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_BCC, "full_address_bcc")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_BODY, "preview_text")); //TODO check + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_IS_READ, "mail_status")); //TODO 1:seen, 2:deleted, 4:flagged, 8:answered, 20:draft + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_PRIORITY, "priority")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_SUBJECT, "subject")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_TYPE, "type")); + + attributeMap.insert( + std::pair( + ConversationFilterValidatorFactory::ATTRIBUTE_MESSAGE_COUNT, "thread_item_count")); + } + + void MessageQueryGenerator::setSmsMmsAttributeMap(){ + LogDebug("<<<"); + attributeMap.clear(); + + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_ID, "A.MSG_ID")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_FOLDER, "A.FOLDER_ID")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_TIMESTAMP, "A.DISPLAY_TIME")); +//TODO check sms mms attribute frome, to, cc, bcc + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_FROM, "B.ADDRESS_VAL")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_TO, "B.ADDRESS_VAL")); +// attributeMap.insert( +// std::pair( +// MessageFilterValidatorFactory::ATTRIBUTE_CC, "full_address_cc")); +// attributeMap.insert( +// std::pair( +// MessageFilterValidatorFactory::ATTRIBUTE_BCC, "full_address_bcc")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_BODY, "A.MSG_TEXT")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_IS_READ, "A.READ_STATUS")); //TODO 1:seen, 2:deleted, 4:flagged, 8:answered, 20:draft + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_PRIORITY, "A.PRIORITY")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_SUBJECT, "A.SUBJECT")); + attributeMap.insert( + std::pair( + MessageFilterValidatorFactory::ATTRIBUTE_TYPE, "A.MAIN_TYPE")); + + LogDebug(">>"); + } + + void MessageQueryGenerator::initAttributeMap(){ + switch (m_mode){ + case MODE_EMAIL: + LogDebug("MODE_EMAIL"); + setEmailAttributeMap(); + break; + case MODE_SMS_MMS: + LogDebug("MODE_SMS_MMS"); + setSmsMmsAttributeMap(); + break; + default: //TODO throw exception + ; + } + } + + void MessageQueryGenerator::visitPreComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + m_queryVector.push_back("("); + LogDebug(">>>"); + } + + void MessageQueryGenerator::visitInComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + + if(m_typeProcessing == 1){ + m_typeProcessing = 0; + + if(type != INTERSECTION_FILTER){ + LogError("[ERROR] >>> invalid Filter type:" << type); + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "invalid Fiilter Type"); + } + + LogDebug(">>>"); + return; + } + + if(type == INTERSECTION_FILTER){ + m_queryVector.push_back("AND"); + } +// else if(type == UNION_FILTER){ +// m_queryVector.push_back("OR"); +// } + else{ + LogError("[ERROR] invalid Filter type:" << type); + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "invalid Fiilter Type"); + } + + LogDebug(">>>"); + } + + void MessageQueryGenerator::visitPostComposite(Api::Tizen::FilterType& type, int depth){ + LogDebug("<<<"); + if(m_typeProcessing == 1){ + m_typeProcessing = 0; + m_queryVector.erase(m_queryVector.end()); + }else{ + } + + m_queryVector.push_back(")"); + LogDebug(">>>"); + } + + std::string MessageQueryGenerator::convertToEmfAttrName(std::string attrName){ + LogDebug("<<< attrName:[" << attrName << "]"); + + std::string retString; + + std::map::iterator it = attributeMap.find(attrName); + if(it == attributeMap.end()){ + MsgLogWanning("[WANNING] attribute not found : ["<< attrName << "]"); + }else{ + retString = static_cast(attributeMap.find(attrName)->second); + } + + LogDebug(">> retString:[" << retString << "]"); + return retString; + } + + std::string MessageQueryGenerator::createTimeString(std::string& timeString) + { + LogDebug("<<< timeString:[" << timeString << "]"); + + size_t pos = timeString.find("-",0); + while(pos!= std::string::npos){ + timeString.erase(pos,1); + pos = timeString.find('-',0); + } + + LogDebug(">>> timeString:[" << timeString << "]"); + return timeString; + } + + std::string MessageQueryGenerator::createFolderType(std::string& value) + { + LogDebug("<<< value:[" << value << "]"); + std::string retFolderType; + std::ostringstream outstream; + + if(value.compare("INBOX") == 0){ + outstream << EMF_MAILBOX_TYPE_INBOX; + }else if(value.compare("OUTBOX") == 0){ + outstream << EMF_MAILBOX_TYPE_OUTBOX; + }else if(value.compare("DRAFTBOX") == 0){ + outstream << EMF_MAILBOX_TYPE_DRAFT; + }else if(value.compare("SENTBOX") == 0){ + outstream << EMF_MAILBOX_TYPE_SENTBOX; + }else{ + LogDebug("[ERROR] unsupported type:["<< value << "]"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "invalid folder id"); + } + + retFolderType = outstream.str(); + + LogDebug(">>> retFolderType:[" << retFolderType << "]"); + return retFolderType; + } + + std::string MessageQueryGenerator::createPriorityTypeForEmail(std::string& value) + { + LogDebug("<<< value:[" << value << "]"); + std::string retPriorityType; + + if(value.compare("true")==0){ + retPriorityType = "1"; + }else{ + retPriorityType = "3 OR priority=5"; + } + + return retPriorityType; + } + + std::string MessageQueryGenerator::createPriorityTypeForSmsMms(std::string& value){ + LogDebug("<<< value:[" << value << "]"); + std::string retPriorityType; + + if(value.compare("true")==0){ + retPriorityType = "1"; + }else if(value.compare("false")==0){ + retPriorityType = "0"; + }else{ + LogError(">>> invalid value:[" << value << "]"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "unsupported value"); + } + + return retPriorityType; + } + + + std::string MessageQueryGenerator::convertToTimeFormat(const std::string& timeString){ + LogDebug("<<< timeString:[" << timeString << "]"); + + std::string retString; + retString.append("'"); + + int yearLength = 4; + int nextStart = 0; + retString.append(timeString.substr(0, yearLength)); + retString.append("-"); + nextStart = nextStart + yearLength; + + int monthLength = 2; + retString.append(timeString.substr(nextStart, monthLength)); + retString.append("-"); + nextStart = nextStart + monthLength; + + int dateLength = 2; + retString.append(timeString.substr(nextStart, dateLength)); + retString.append(" "); + nextStart = nextStart + dateLength; + + int hourLength = 2; + retString.append(timeString.substr(nextStart, hourLength)); + retString.append(":"); + nextStart = nextStart + hourLength; + + int minuteLength = 2; + retString.append(timeString.substr(nextStart, minuteLength)); + retString.append(":"); + nextStart = nextStart + minuteLength; + + int secondLength = 2; + retString.append(timeString.substr(nextStart, secondLength)); + retString.append("'"); + + LogDebug(">>> retString:[" << retString << "]"); + return retString; + } + + //convert from '20111115000000' to 2011-11-15 00:00:00 + std::string MessageQueryGenerator::createDateTimeTypeForSmsMms(Api::Tizen::AnyPtr& value){ + LogDebug("<<< value:[" << value->toString() << "]"); + + std::string tmpValueString = value->toString(); + std::string secondsSinceType; + secondsSinceType.append("strftime('%s', "); //SQL time format function + if(m_mode == MODE_SMS_MMS){ + tmpValueString = convertToTimeFormat(tmpValueString); + } + + secondsSinceType.append(tmpValueString); + secondsSinceType.append(")"); + + LogDebug(">>> retPriorityType:[" << secondsSinceType << "]"); + return secondsSinceType; + } + + std::string MessageQueryGenerator::createDateTimeTypeForEmail(Api::Tizen::AnyPtr& value) + { + LogDebug("<<< value:[" << value->toString() << "]"); + + if(value->getType() != PrimitiveType_Time){ + LogError("[ERROR]>> invalid type"); + return NULL; + } + + std::string retPriorityType; + retPriorityType = value->toString(); + + return retPriorityType; + } + + std::string MessageQueryGenerator::convertBooleanStringToIntegerString(std::string& booleanString){ + std::string retString; + + if(booleanString.compare("true") == 0){ + retString = "1"; + }else if(booleanString.compare("false") == 0){ + retString = "0"; + }else{ + LogError("invalid booleanString:[" << booleanString << "]"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "invalid booleanString :[" + booleanString + "]"); + } + return retString; + } + + std::string MessageQueryGenerator::getMatchExactlyClause(std::string& attrName, Api::Tizen::AnyPtr& value) + { + std::string retClause; + std::string valueString = value->toString(); + std::string emfAttributeName = convertToEmfAttrName(attrName); + + do{ + if(m_mode == MODE_EMAIL){ + if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_FROM)==0){ + retClause = emfAttributeName + " LIKE '%%<" + valueString +">'"; + break; + }else if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_TIMESTAMP)==0){ + retClause = emfAttributeName + "=" + createDateTimeTypeForEmail(value); + break; + }else if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_PRIORITY)==0){ + retClause = emfAttributeName + "=" + createPriorityTypeForEmail(valueString); + break; + } + }else if(m_mode == MODE_SMS_MMS){ + if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_FROM)==0){ + retClause = "("+emfAttributeName + " ='"+ valueString + "' AND " + getMessageDirectionString() + "=1)"; + break; + }else if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_TO)==0){ + retClause = "("+emfAttributeName + " ='"+ valueString + "' AND " + getMessageDirectionString() + "=0)"; + break; + }else if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_TIMESTAMP)==0){ + retClause = emfAttributeName + "=" + createDateTimeTypeForSmsMms(value); //TODO need to check + break; + }else if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_PRIORITY)==0){ + retClause = emfAttributeName + "=" + createPriorityTypeForSmsMms(valueString); + break; + } + } + + if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_IS_READ)==0){ + retClause = emfAttributeName + "=" + convertBooleanStringToIntegerString(valueString); + } else if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_FOLDER)==0){ + retClause = emfAttributeName + "=" + createFolderType(valueString); + }else{ + retClause = emfAttributeName + " = '" + value->toString() + "'"; //TODO need to check + } + }while(false); + + return retClause; + } + + std::string MessageQueryGenerator::getMatchStartsWithClause(std::string& attrName, TizenApis::Api::Tizen::AnyPtr& value){ + std::string retClause; + std::string valueString = value->toString(); + std::string emfAttributeName = convertToEmfAttrName(attrName); + + do{ + if(m_mode == MODE_EMAIL){ + }else if(m_mode == MODE_SMS_MMS){ + if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_FROM)==0){ + retClause.append("(" + emfAttributeName + " LIKE '" + value->toString() + + "%%' AND " + getMessageDirectionString() + "=1) "); + break; + }else if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_TO)==0){ + retClause.append("(" + emfAttributeName + " LIKE '" + value->toString() + + "%%' AND " + getMessageDirectionString() +"=0) "); + break; + } + } + + retClause.append(emfAttributeName + " LIKE '" + value->toString() +"%%'"); + }while(false); + + return retClause; + } + + std::string MessageQueryGenerator::getMessageDirectionString(){ + return MessageQueryGenerator::STRING_DIRECTION; + } + + std::string MessageQueryGenerator::getMatchEndsWithClause(std::string& attrName, TizenApis::Api::Tizen::AnyPtr& value){ + std::string retClause; + std::string valueString = value->toString(); + std::string emfAttributeName = convertToEmfAttrName(attrName); + + do{ + if(m_mode == MODE_EMAIL){ + }else if(m_mode == MODE_SMS_MMS){ + if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_FROM)==0){ + retClause.append("(" + emfAttributeName + " LIKE '%%" + value->toString() + + "' AND "+ getMessageDirectionString() + "=1) "); + break; + }else if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_TO)==0){ + retClause.append("(" + emfAttributeName + " LIKE '%%" + value->toString() + + "' AND " + getMessageDirectionString() + "=0) "); + break; + } + } + + retClause.append(emfAttributeName + " LIKE '%%" + value->toString() +"'"); + }while(false); + + return retClause; + } + + std::string MessageQueryGenerator::getMatchContainsClause(std::string& attrName, TizenApis::Api::Tizen::AnyPtr& value){ + std::string retClause; + std::string valueString = value->toString(); + std::string emfAttributeName = convertToEmfAttrName(attrName); + + do{ + if(m_mode == MODE_EMAIL){ + }else if(m_mode == MODE_SMS_MMS){ + if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_FROM)==0){ + retClause.append("(" + emfAttributeName + " LIKE '%%" + value->toString() + + "%%' AND " + getMessageDirectionString() + "=1) "); + break; + }else if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_TO)==0){ + retClause.append("(" + emfAttributeName + " LIKE '%%" + value->toString() + + "%%' AND " + getMessageDirectionString() + "=0) "); + break; + } + } + + retClause.append(emfAttributeName + " LIKE '%%" + value->toString() +"%%'"); + }while(false); + + return retClause; + } + + void MessageQueryGenerator::visitAttribute(std::string& attrName, + Api::Tizen::AnyArrayPtr& values, std::string& matchFlag, bool caseSensitive, int depth){ + LogDebug("<<< attrName:[" << attrName << "], matchFlag:[" << matchFlag << "]"); + LogDebug("values->size():" << values->size()); + + Api::Tizen::FilterType filterType = UNION_FILTER; + + if(matchFlag.compare("EXIST")==0){ + //TODO implement for EXIST + }else if(values->size() == 1){ + AnyPtr matchValue = values->at(0); + visitAttributeEach(attrName, matchValue, matchFlag, depth); + }else{ + visitPreComposite(filterType, depth); + + AnyArray::iterator iter; + for(iter=values->begin(); iter!= values->end(); iter++){ + + if(iter != values->begin()){ + + visitInComposite(filterType, depth); + } + + AnyPtr matchValue = *iter; + visitAttributeEach(attrName, matchValue, matchFlag, depth); + } + + visitPostComposite(filterType, depth); + } + LogDebug(">>>"); + } + + int MessageQueryGenerator::convertMessageType(std::string& stringType){ + LogDebug("<<< stringType:[" << stringType << "]"); + + int retMessageType = -1; + + if(stringType.compare("SMS") ==0){ + retMessageType = Api::Messaging::SMS; + }else if(stringType.compare("MMS") ==0){ + retMessageType = Api::Messaging::MMS; + }else if(stringType.compare("EMAIL") ==0){ + retMessageType = Api::Messaging::EMAIL; + }else{ + MsgLogError("invalid type:[" << stringType << "]"); + return -1; + } + + LogDebug(">>> retMessageType:" << retMessageType); + return retMessageType; + } + + + void MessageQueryGenerator::visitAttributeEach(std::string& attrName, Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth){ + LogDebug("<<< attrName:[" << attrName << "], value:[" << value->toString() << "]"); + + if(attrName.compare("type")==0){ + m_typeProcessing = 1; + m_currentType = value->toString(); + + m_messageType = convertMessageType(m_currentType); + + LogDebug(">>> skip type"); + return; + } + + std::string emfAttributeName = convertToEmfAttrName(attrName); + +// if(emfAttributeName == NULL){ +// LogDebug(">>> emfAttributeName is NULL"); +// return; +// } + std::string tmpStringBuffer; + + if(matchFlag.compare(STRING_MATCH_EXCACTLY) == 0){ + LogDebug("STRING_MATCH_EXCACTLY"); + tmpStringBuffer.append(getMatchExactlyClause(attrName, value)); + }else if(matchFlag.compare(STRING_MATCH_CONTAINS) == 0){ + LogDebug("STRING_MATCH_CONTAINS"); + tmpStringBuffer.append(getMatchContainsClause(attrName, value)); + }else if(matchFlag.compare(STRING_MATCH_STARTSWITH) == 0){ + LogDebug("STRING_MATCH_STARTSWITH"); + tmpStringBuffer.append(getMatchStartsWithClause(attrName, value)); + }else if(matchFlag.compare(STRING_MATCH_ENDSWITH) == 0){ + LogDebug("STRING_MATCH_ENDSWITH"); + tmpStringBuffer.append(getMatchEndsWithClause(attrName, value)); + }else{ + LogDebug("[ERROR]invalid match flag[" << matchFlag << "]"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "invalid match flag:[" + matchFlag + "]"); + } +// else if(iter->find(MATCH_CASESENSITIVE)){ //TODO check case sensitive +// } + m_queryVector.push_back(tmpStringBuffer); + LogDebug(">>>"); + } + + void MessageQueryGenerator::visitAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth) { + LogDebug("<<< sttrName:[" << attrName <<"]"); + LogDebug("initialVAlue:[" << initialValue->toString() << "]"); + LogDebug("endValue:[" << endValue->toString() << "]"); + + std::string tmpStringBuffer; + + std::string emfAttributeName = convertToEmfAttrName(attrName); + if(attrName.compare(MessageFilterValidatorFactory::ATTRIBUTE_TIMESTAMP)==0){ + if(m_mode == MODE_EMAIL){ + tmpStringBuffer.append(emfAttributeName + " BETWEEN " + initialValue->toString() + " AND " + endValue->toString()); + }else if(m_mode == MODE_SMS_MMS){ + tmpStringBuffer.append(emfAttributeName + " BETWEEN " + + createDateTimeTypeForSmsMms(initialValue) + " AND " + + createDateTimeTypeForSmsMms(endValue)); + } + } + + m_queryVector.push_back(tmpStringBuffer); + LogDebug(">>>"); + } + + std::string MessageQueryGenerator::getQueryFromVector() + { + std::string retString; + + std::vector::const_iterator it = m_queryVector.begin(); + while(it != m_queryVector.end()){ + retString.append(*it); + retString.append(" "); + it++; + } + + LogDebug(">>> retString:" << retString); + return retString; + } + + std::string MessageQueryGenerator::getQuery(){ + std::stringstream buffer; + + m_query.append(getQueryFromVector()); + + if(m_query.compare(getQueryPrefix())==0){ + return ""; + }else{ + if(m_sortMode != NULL){ + std::string platformAttrName = convertToEmfAttrName(m_sortMode->getAttributeName()); + std::string sortModeString; + if(m_sortMode->getOrder() == ASCENDING_SORT_ORDER){ + sortModeString = "ASC"; + }else{ + sortModeString = "DESC"; + } + + buffer << " ORDER BY " << platformAttrName << " " << sortModeString; + if(m_limit != 0){ + buffer << " LIMIT " << m_offset << "," << m_limit; + } + } + + m_query.append(getQuerySuffix()); + m_query.append(buffer.str()); + return m_query; + } + } + + std::string MessageQueryGenerator::getQueryPrefix(){ + return MessageQueryGenerator::STRING_WHERE; + } + + std::string MessageQueryGenerator::getQuerySuffix(){ + return MessageQueryGenerator::STRING_SUFFIX; + } + + + + } + } //namespace Platform +} //namespace WrtPlugins diff --git a/src/platform/Tizen/Messaging/MessageQueryGenerator.h b/src/platform/Tizen/Messaging/MessageQueryGenerator.h new file mode 100755 index 0000000..101973c --- /dev/null +++ b/src/platform/Tizen/Messaging/MessageQueryGenerator.h @@ -0,0 +1,141 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * MessageQueryGenerator.h + * + * Created on: 2011. 10. 28. + * Author: sangtai + */ + +#ifndef MESSAGEQUERYGENERATOR_H_ +#define MESSAGEQUERYGENERATOR_H_ + +#include +#include + +#include + +namespace TizenApis { + namespace Platform { + namespace Messaging { + + class MessageQueryGenerator: public TizenApis::Api::Tizen::IFilterVisitor{ + + public: + enum QueryGeneratorMode{ + MODE_EMAIL, + MODE_SMS_MMS + }; + + protected: + std::map attributeMap; + + private: + QueryGeneratorMode m_mode; + std::string m_query; + std::vector m_queryVector; + + int m_messageType; + + std::vector typeVector; + + Api::Tizen::SortModePtr m_sortMode; + long m_limit; + long m_offset; + + int m_typeProcessing; + std::string m_currentType; + + static const std::string STRING_MATCH_EXCACTLY; + static const std::string STRING_MATCH_CONTAINS; + static const std::string STRING_MATCH_STARTSWITH; + static const std::string STRING_MATCH_ENDSWITH; + static const std::string STRING_MATCH_CASESENSITIVE; + static const std::string STRING_WHERE; + static const std::string STRING_SUFFIX; + static const std::string STRING_DIRECTION; + + static const int MESSAGE_TYPE_NOT_INITIALIZED; + + public: + MessageQueryGenerator(); + MessageQueryGenerator(const Api::Tizen::SortModePtr& sortMode, const long limit, const long offset); + virtual ~MessageQueryGenerator(); + + void visitPreComposite(Api::Tizen::FilterType& type, int depth); + void visitInComposite(Api::Tizen::FilterType& type, int depth); + void visitPostComposite(Api::Tizen::FilterType& type, int depth); + void visitAttribute(std::string& attrName, + Api::Tizen::AnyArrayPtr& values, std::string& matchFlag, bool caseSensitive, int depth); + void visitAttributeRange(std::string& attrName, Api::Tizen::AnyPtr& initialValue, Api::Tizen::AnyPtr& endValue, int depth); + + std::string getQuery(); + +// bool containMailType(); +// bool containType(int type); + int getMessageType(){ + return m_messageType; + }; + + void setMode(QueryGeneratorMode mode ){ + m_mode = mode; + } + + QueryGeneratorMode getMode(){ + return m_mode; + } + + void reset(QueryGeneratorMode mode); + + protected: + virtual void setEmailAttributeMap(); + virtual void setSmsMmsAttributeMap(); + virtual std::string getMatchExactlyClause(std::string& attrName, Api::Tizen::AnyPtr& value); + virtual std::string getQueryPrefix(); + virtual std::string getQuerySuffix(); + virtual std::string getMessageDirectionString(); + + std::string convertToEmfAttrName(std::string attrName); + + void visitAttributeEach(std::string& attrName, Api::Tizen::AnyPtr& value, std::string& matchFlag, int depth); + + private: + std::string getMatchStartsWithClause(std::string& attrName, Api::Tizen::AnyPtr& value); + std::string getMatchEndsWithClause(std::string& attrName, Api::Tizen::AnyPtr& value); + std::string getMatchContainsClause(std::string& attrName, Api::Tizen::AnyPtr& value); + + std::string createTimeString(std::string& timeString); + std::string createFolderType(std::string& value); + std::string createPriorityTypeForEmail(std::string& value); + std::string createPriorityTypeForSmsMms(std::string& value); + std::string createDateTimeTypeForEmail(Api::Tizen::AnyPtr& value); + + std::string createDateTimeTypeForSmsMms(Api::Tizen::AnyPtr& value); + + std::string convertToTimeFormat(const std::string& timeString); + std::string convertBooleanStringToIntegerString(std::string& booleanString); + + void initAttributeMap(); + std::string getQueryFromVector(); + + int convertMessageType(std::string& stringType); + }; + + typedef DPL::SharedPtr MessageQueryGeneratorPtr; + } // namespace Platform +} // namespace WrtPlugins +} +#endif /* MESSAGEQUERYGENERATOR_H_ */ diff --git a/src/platform/Tizen/Messaging/Messaging.cpp b/src/platform/Tizen/Messaging/Messaging.cpp new file mode 100755 index 0000000..7727097 --- /dev/null +++ b/src/platform/Tizen/Messaging/Messaging.cpp @@ -0,0 +1,2209 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Messaging.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include + +#include +#include +#include +#include +#include "Messaging.h" +#include "Sms.h" +#include "Mms.h" +#include "BinarySms.h" +#include "Email.h" +#include "EmailConverter.h" + +#include "API/Messaging/log.h" + + + +#include "API/Messaging/StorageChangesMessageFilterValidatorFactory.h" +#include "API/Messaging/StorageChangesConversationFilterValidatorFactory.h" +#include "API/Messaging/StorageChangesFolderFilterValidatorFactory.h" +#include "MessageQueryGenerator.h" + +#include "ConversationQueryGenerator.h" +#include "FolderQueryGenerator.h" + +#include "messageDB/MessageStorageReader.h" + +extern "C" { +#include +#include +#include +#include +#include +} + +#include +#include "Conversation.h" +#include "MessageFolder.h" + + +#define LOG_ENTER LogDebug("---> ENTER"); +#define LOG_EXIT LogDebug("---> EXIT"); + + +using namespace std; +using namespace TizenApis::Api::Messaging; +using namespace TizenApis::Api::Tizen; +using namespace WrtDeviceApis::Commons; + +namespace { +const char* DBUS_INTERFACE_EMAIL_RECEIVED = "User.Email.StorageChange"; +const char* DBUS_FILTER_EMAIL_RECEIVED = + "type='signal',interface='User.Email.StorageChange'"; + +const int MESSAGE_FIND_LIMIT = 100; +} + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +int Messaging::m_currentEmailAccountId = 0; +DPL::Atomic Messaging::m_objCounter; + +Messaging& Messaging::getInstance() +{ + static Messaging instance; + return instance; +} + +Messaging::Messaging() : + m_onMessageReceivedHandleMgr(NULL), + m_dbusConnection(new DBus::Connection()), + m_dbusWorkerThread(new DPL::Thread()) +{ + Try + { + const vector accounts = getEmailAccounts(); + LogDebug("Number of emails account=" << accounts.size()); + if (accounts.size() > 0) { + // set default email account - first from the list + setCurrentEmailAccount(accounts[0]); + } else { + LogError("no default email account set"); + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("No email accounts available"); + } + + Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + LogError("No email accounts available"); + //current email not configured, skipped + } + + Catch(WrtDeviceApis::Commons::UnknownException) { + LogError("unknown error"); + } + + // Begin service for email management ?? pmi question if it should be added before email actions + if (0 == m_objCounter) { + int error = email_service_begin(); + if (EMF_ERROR_NONE != error) { + LogError("email_service_begin() returned error " << error); + } else { + LogInfo("email_service_begin() executed without error"); + } + } + ++m_objCounter; + + m_dbusWorkerThread->Run(); + m_dbusConnection->setWorkerThread(m_dbusWorkerThread); + m_dbusConnection->addFilter(DBUS_FILTER_EMAIL_RECEIVED); + m_dbusConnection->AddListener(this); +} + +Messaging::~Messaging() +{ + // Endservice for email management + m_dbusConnection->RemoveListener(this); + m_dbusConnection->setWorkerThread(NULL); + m_dbusWorkerThread->Quit(); + delete m_dbusWorkerThread; + + if (!--m_objCounter) { + int error = email_service_end(); + if (EMF_ERROR_NONE != error) { + LogError("email_service_end() returned error " << error); + } else { + LogDebug("email_service_end() executed without error"); + } + } +} + +void Messaging::getNumberOfMessages(MessageType msgType, + FolderType folder, + int* readed, + int* unReaded) +{ + if (NULL == readed || + NULL == unReaded) { + LogError("output pointers are NULL"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + *readed = 0; + *unReaded = 0; + if (Api::Messaging::SMS == msgType) { + getNumberOfSms(folder, readed, unReaded); + } else if (Api::Messaging::MMS == msgType) { + getNumberOfMms(folder, readed, unReaded); + } else if (Api::Messaging::EMAIL == msgType) { + getNumberOfEmails(folder, readed, unReaded); + } else { + LogError("wrong message type"); + Throw(WrtDeviceApis::Commons::PlatformException); + } +} + +vector Messaging::findMessages(const vector& msgTypes, + const string &folder, + const Api::Tizen::FilterPtr& filter) +{ + LogDebug("enter"); + vector retVal; + back_insert_iterator< vector > biit(retVal); + vector::const_iterator it = msgTypes.begin(); + for (; it != msgTypes.end(); ++it) { + LogDebug("Finding messages (" << *it << ") in folder: " << folder); + vector result; + + switch (*it) { + case SMS: + { + FolderType folderEnum = Sms::toFolder(folder); + result = findSms(folderEnum, filter); + break; + } + case MMS: + { + FolderType folderEnum = Mms::toFolder(folder); + result = findMms(folderEnum, filter); + break; + } + case EMAIL: + { + result = findEmail(folder, filter); + break; + } + default: + LogError("message type unknown"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + LogDebug("Found: " << result.size()); + copy(result.begin(), result.end(), biit); + } + + return retVal; +} + +std::string Messaging::generateFilterSql(const Api::Tizen::FilterPtr& filter){ + LogDebug("<<<"); + std::string filterSql; + + MessageQueryGeneratorPtr queryGenerator(new MessageQueryGenerator()); + IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast(queryGenerator); + filter->travel(filterVisitor, 0); + filterSql = queryGenerator->getQuery(); + + LogDebug(">>> filterSql:[" << filterSql << "]"); + return filterSql; +} + + vector Messaging::findMessages(const vector& msgTypes, FolderType folder, + const Api::Tizen::FilterPtr& filter) +{ + LogDebug("enter"); + vector retVal; + back_insert_iterator< vector > biit(retVal); + + std::string filterSql = generateFilterSql(filter); + + + + vector::const_iterator it = msgTypes.begin(); + for (; it != msgTypes.end(); ++it) { + LogDebug("Finding messages (" << *it << ") in folder: " << folder); + vector(Messaging::*findFnPtr)(Api::Messaging::FolderType folder, const Api::Tizen::FilterPtr& filter) = NULL; + + switch (*it) { + case SMS: + { + findFnPtr = &Messaging::findSms; + break; + } + case MMS: + { + findFnPtr = &Messaging::findMms; + break; + } + case EMAIL: + { + findFnPtr = &Messaging::findEmail; + break; + } + default: + LogError("message type unknown"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + vector result = (this->*findFnPtr)(folder, filter); + LogDebug("Found: " << result.size()); + copy(result.begin(), result.end(), biit); + } + + return retVal; +} + + void Messaging::printErrorMessage(int errorCode){ + switch(errorCode){ + case EMF_ERROR_MAIL_NOT_FOUND:{ + LogDebug("EMF_ERROR_MAIL_NOT_FOUND"); + break; + } + case EMF_ERROR_DB_FAILURE:{ + LogDebug("EMF_ERROR_DB_FAILURE"); + break; + } + default:{ + LogDebug("other error message:" << errorCode); + } + } + } + + vector Messaging::createVectorFromeMessageList(const MSG_LIST_S& message_list){ + LogDebug("<<<"); + + vector retVal; + LogDebug("message_list.nCount:" << message_list.nCount); + for (int i = 0; i < message_list.nCount; i++) { +// int msgId = msg_get_message_id(message_list.msgInfo[i]); + + string addressVal = msg_get_ith_address(message_list.msgInfo[i], 0); + LogDebug("<<< addressVal:" << addressVal); + + int msgType = msg_get_message_type(message_list.msgInfo[i]); + MessageType webApiMsgType; + + switch(msgType){ + case MSG_TYPE_SMS:{ + webApiMsgType = Api::Messaging::SMS; + break; + } + case MSG_TYPE_MMS:{ + webApiMsgType = Api::Messaging::MMS; + break; + } + default:{ + LogError("[ERROR]invalid message type:" << msgType); + continue; + } + } + + int l_msgId = msg_get_message_id(message_list.msgInfo[i]); + Api::Messaging::IMessagePtr msg; + msg = MessageFactory::createMessage(webApiMsgType, l_msgId); + retVal.push_back(msg); + } //for + + LogDebug(">>>"); + return retVal; + } + + std::vector Messaging::createVectorFromeThreadViewList(const MSG_THREAD_VIEW_LIST_S& threadViewList){ + vector recVec; + + if (threadViewList.nCount <= 0) { + LogDebug("Empty..."); + } else { + for (int i = 0; i < threadViewList.nCount; i++) { + Api::Messaging::IConversationPtr convPtr(new Conversation(i)); + recVec.push_back(convPtr); + } + } + + return recVec; + } + + vector Messaging::querySmsMmsMessages(const std::string& queryString){ + LogDebug("<<< queryString:[" << queryString <<"]"); + + vector retVal; + MSG_LIST_S message_list = {0, NULL}; + + Try{ + MSG_ERROR_T res = MSG_ERR_UNKNOWN; + + MessageStorageReader reader; + reader.MsgStoConnectDB(); + res = reader.queryMessage(queryString, &message_list); + + if (MSG_SUCCESS != res) { + LogError("msg_get_folder_view_list failed " << res); + Throw(WrtDeviceApis::Commons::PlatformException); + } + reader.MsgStoDisconnectDB(); + + retVal = createVectorFromeMessageList(message_list); + + msg_release_message_list(&message_list); + }Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Problem with message creation, cleaning"); + if (message_list.nCount) { + msg_release_message_list(&message_list); + } + throw; + } //Catch + + LogDebug(">>>"); + return retVal; + } + +vector Messaging::querySmsMmsConversation(const std::string& sqlWhereClause){ + LogDebug("sqlWhereClause:[" << sqlWhereClause << "]"); + + std::vector recVec; + MSG_THREAD_VIEW_LIST_S threadViewList; + + MSG_ERROR_T res = MSG_ERR_UNKNOWN; + + MessageStorageReader reader; + reader.MsgStoConnectDB(); + res = reader.queryConversation(sqlWhereClause, &threadViewList); + + if (MSG_SUCCESS != res) { + LogError("queryConversation failed:" << res); + Throw(WrtDeviceApis::Commons::PlatformException); + } + reader.MsgStoDisconnectDB(); + + recVec = createVectorFromeThreadViewList(threadViewList); + + msg_release_thread_view_list(&threadViewList); + + LogDebug(">>>"); + return recVec; +} + +vector Messaging::queryEmailConversation(const std::string& sqlWhereClause){ + LogDebug("sqlWhereClause:[" << sqlWhereClause << "]"); + + std::vector emailResultVector; + emf_mail_list_item_t* mailList = NULL; + int mailListCount = 0; + int errCode = 0; + errCode = email_query_message_ex(const_cast(sqlWhereClause.c_str()), &mailList, &mailListCount); + + if(errCode != EMF_ERROR_NONE){ + LogError("[ERROR]email_query_message_ex failed:" << errCode); + printErrorMessage(errCode); + if (mailList != NULL){ + free(mailList); + } + }else{ + LogDebug("message found mailListCount:" << mailListCount); + std::map checkUnique; + + for(int i=0; igetResult() == true) + { + emailResultVector.push_back(convPtr); + } + } //if + }//for + }//if + + if (mailList != NULL){ + free(mailList); + } + + LogDebug(">>>"); + return emailResultVector; +} + +vector Messaging::queryEmailMessage(const std::string& sqlWhereClause){ + LogDebug("sqlWhereClause:[" << sqlWhereClause << "]"); + + vector emailResultVector; + + emf_mail_list_item_t* mailList = NULL; + int mailListCount = 0; + int errCode = 0; + errCode = email_query_message_ex(const_cast(sqlWhereClause.c_str()), &mailList, &mailListCount); + + if(errCode != EMF_ERROR_NONE){ + LogError("[ERROR]email_query_message_ex failed:" << errCode); + printErrorMessage(errCode); + if (mailList != NULL) { + free(mailList); + } + }else{ + LogDebug("message found mailListCount:" << mailListCount); + + for(int i=0; i>>"); + return emailResultVector; +} + +vector Messaging::findMessages(const Api::Tizen::FilterPtr& filter){ + LogDebug("<<<"); + + vector retVal; + std::string filterSql; + + MessageQueryGeneratorPtr queryGenerator(new MessageQueryGenerator()); + + IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast(queryGenerator); + filter->travel(filterVisitor, 0); + filterSql = queryGenerator->getQuery(); + LogDebug("filterSql:[" << filterSql <<"]"); + + int messageType = queryGenerator->getMessageType(); + switch(messageType){ + case Api::Messaging::EMAIL: + LogDebug("message type is EMAIL:[" << messageType <<"]"); + retVal = queryEmailMessage(filterSql); + break; + + case Api::Messaging::SMS: + case Api::Messaging::MMS: + LogDebug("message type is SMS or MMS:[" << messageType <<"]"); + queryGenerator->reset(MessageQueryGenerator::MODE_SMS_MMS); + filterVisitor = DPL::StaticPointerCast(queryGenerator); + filter->travel(filterVisitor); + filterSql = queryGenerator->getQuery(); + retVal = querySmsMmsMessages(filterSql); + break; + + default: + LogError("[ERROR] >>> invlid message type:[" << messageType <<"]"); + return retVal; + } + + LogDebug(">>>"); + return retVal; +} + +//TODO refactoring +vector Messaging::findMessages(const Api::Tizen::FilterPtr& filter, const Api::Tizen::SortModePtr& sortMode, const long limit, const long offset) +{ + LogDebug("<<<"); + + vector retVal; + std::string filterSql; + + MessageQueryGeneratorPtr queryGenerator(new MessageQueryGenerator(sortMode, limit, offset)); + + IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast(queryGenerator); + filter->travel(filterVisitor, 0); + filterSql = queryGenerator->getQuery(); + LogDebug("filterSql:[" << filterSql <<"]"); + + int messageType = queryGenerator->getMessageType(); + switch(messageType){ + case Api::Messaging::EMAIL: + LogDebug("message type is EMAIL:[" << messageType <<"]"); + retVal = queryEmailMessage(filterSql); + break; + + case Api::Messaging::SMS: + case Api::Messaging::MMS: + LogDebug("message type is SMS or MMS:[" << messageType <<"]"); + queryGenerator->reset(MessageQueryGenerator::MODE_SMS_MMS); + filterVisitor = DPL::StaticPointerCast(queryGenerator); + filter->travel(filterVisitor); + filterSql = queryGenerator->getQuery(); + retVal = querySmsMmsMessages(filterSql); + break; + + default: + MsgLogError("[ERROR] >>> invlid message type:[" << messageType <<"]"); + return retVal; + } + + LogDebug(">>>"); + return retVal; +} + +vector Messaging::getMessageIds(MessageType msgType, + FolderType folder) +{ + switch (msgType) { + case SMS: + return getSmsIds(folder); + case MMS: + return getMmsIds(folder); + case EMAIL: + return getEmailIds(folder); + default: + LogError("not supported message type"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } +} + +vector Messaging::getSmsIds(FolderType folder) +{ + vector retVal; + msg_message_t msg = msg_new_message(); + MSG_LIST_S folder_list_view = { 0, NULL }; + + Try + { + const MSG_SORT_RULE_S sort_rules = { MSG_SORT_BY_DISPLAY_TIME, true }; + MSG_ERROR_T res = MSG_ERR_UNKNOWN; + const MSG_FOLDER_ID_T platformFolder = convertFolderToPlatform(folder); + res = msg_get_folder_view_list( + MsgGetCommonHandle(), platformFolder, &sort_rules, + &folder_list_view); + + if (MSG_SUCCESS != res) { + LogError("msg_Get_folder_view_list failed" << res); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + for (int i = 0; i < folder_list_view.nCount; i++) { + if (MSG_TYPE_SMS == + msg_get_message_type(folder_list_view. + msgInfo[i])) { + int l_msgId = msg_get_message_id( + folder_list_view.msgInfo[i]); + ostringstream stream; + stream << l_msgId; + retVal.push_back(stream.str()); + } + } + + msg_release_message_list(&folder_list_view); + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Problem with message creation, cleaning"); + if (folder_list_view.nCount) { + msg_release_message_list(&folder_list_view); + } + if (msg) { + msg_release_message(&msg); + } + throw; + } + + return retVal; +} + +vector Messaging::getMmsIds(FolderType folder) +{ + vector retVal; + msg_message_t msg = msg_new_message(); + MSG_LIST_S folder_list_view = { 0, NULL }; + + Try + { + const MSG_SORT_RULE_S sort_rules = { MSG_SORT_BY_DISPLAY_TIME, true }; + MSG_ERROR_T res = MSG_ERR_UNKNOWN; + const MSG_FOLDER_ID_T platformFolder = convertFolderToPlatform(folder); + res = msg_get_folder_view_list( + MsgGetCommonHandle(), platformFolder, &sort_rules, + &folder_list_view); + + if (MSG_SUCCESS != res) { + LogError("msg_Get_folder_view_list failed" << res); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + for (int i = 0; i < folder_list_view.nCount; i++) { + if (MSG_TYPE_MMS == + msg_get_message_type(folder_list_view. + msgInfo[i])) { + int l_msgId = msg_get_message_id( + folder_list_view.msgInfo[i]); + ostringstream stream; + stream << l_msgId; + retVal.push_back(stream.str()); + } + } + + msg_release_message_list(&folder_list_view); + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Problem with message creation, cleaning"); + if (folder_list_view.nCount) { + msg_release_message_list(&folder_list_view); + } + if (msg) { + msg_release_message(&msg); + } + throw; + } + + return retVal; +} + +vector Messaging::getEmailIds(FolderType folder) +{ + vector retVal; + + //TODO + LogError("TODO"); + Throw(WrtDeviceApis::Commons::UnknownException); + + return retVal; +} + +vector Messaging::getEmailAccounts() const +{ + emf_account_t* accounts = NULL; + int count = 0; + Try { + if (!email_get_account_list(&accounts, &count)) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Couldn't get e-mail accounts."); + } + + if (0 == count) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "No e-mail account found."); + } + + vector result; + for (int i = 0; i < count; ++i) { + Api::Messaging::EmailAccountInfo account(accounts[i].account_id, + accounts[i].user_name, + accounts[i].email_addr); + result.push_back(account); + } + + if (accounts != NULL) { + email_free_account(&accounts, count); + } + + return result; + } + Catch(WrtDeviceApis::Commons::PlatformException) { + if (accounts != NULL) { + email_free_account(&accounts, count); + } + throw; + } +} + +int Messaging::getEmailAccountId(const std::string& account) +{ + int retVal = 0; + string tmpAccount = account; + emf_account_t *pAccountArray = NULL; + int iCount = 0; + + Try + { + if (account.empty()) { + tmpAccount = getCurrentEmailAccount().getAddress(); + if (tmpAccount.empty()) { + LogError( + "current email account is not set, possible that no account created"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + } + + if (!email_get_account_list(&pAccountArray, &iCount)) { + LogError("email_get_account_list error"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + if (0 == iCount) { + LogError("no email account exist"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + for (int i = 0; i < iCount; i++) { + string tmp = pAccountArray[i].email_addr; + if (tmp == tmpAccount) { + m_currentEmailAccountId = pAccountArray[i].account_id; + retVal = m_currentEmailAccountId; + break; + } + } + + if (0 == m_currentEmailAccountId) { + LogError("wrong email account ID"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + if (pAccountArray != NULL) { + LogDebug("free account, ptr=" << pAccountArray); + email_free_account(&pAccountArray, iCount); + } + + if (0 == retVal) { + LogError("no email account created"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("exception catch, platform exception"); + if (pAccountArray != NULL) { + email_free_account(&pAccountArray, iCount); + } + throw; + } + + return retVal; +} + +void Messaging::fetchEmailHeaders() +{ + emf_mailbox_t *mailbox = NULL; + unsigned handle = 0; + mailbox = static_cast(calloc(sizeof (emf_mailbox_t), 1)); + if (!mailbox) { + LogError("calloc failed"); + return; + } + mailbox->account_id = m_currentEmailAccountId; + mailbox->name = strdup(EMF_INBOX_NAME); + if (EMF_ERROR_NONE != email_sync_header(mailbox, &handle)) { + LogError("email_sync_header failed"); + } + email_free_mailbox(&mailbox, 1); +} + +int Messaging::convertFolderToPlatform(const FolderType folder) +{ + MSG_FOLDER_ID_T platfromFolderId; + switch (folder) { + case INBOX: + platfromFolderId = MSG_INBOX_ID; + break; + case DRAFTBOX: + platfromFolderId = MSG_DRAFT_ID; + break; + case OUTBOX: + platfromFolderId = MSG_OUTBOX_ID; + break; + case SENTBOX: + platfromFolderId = MSG_SENTBOX_ID; + break; + case SPAMBOX: + // intentionally not break in platform is no spambox + default: + LogError("Invalid folder: " << folder); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + return platfromFolderId; +} + +int Messaging::convertFolderToPlatform(const std::string &folder) +{ + MSG_FOLDER_LIST_S folderList = { 0, NULL }; + int result = 0; + Try + { + if (MSG_SUCCESS != + msg_get_folder_list(MsgGetCommonHandle(), &folderList)) { + LogError("msg_get_folder_list error"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + for (int i = 0; i < folderList.nCount; ++i) { + if (MSG_FOLDER_TYPE_USER_DEF == + folderList.folderInfo[i].folderType && + NULL != folderList.folderInfo[i].folderName && + folder == folderList.folderInfo[i].folderName) { + result = folderList.folderInfo[i].folderId; + break; + } + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + if (folderList.nCount) { + msg_release_folder_list(&folderList); + } + throw; + } + if (folderList.nCount) { + msg_release_folder_list(&folderList); + } + return result; +} + +void Messaging::addOnMessageReceived( + const Api::Messaging::EmitterMessageReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, int funtionIndex) +{ + LogDebug("ENTER"); + + if(filter != NULL) + { + Try + { + LogDebug("funtionIndex = " << funtionIndex); + bool isValidFilter = validateFilter(filter, funtionIndex); + if(isValidFilter == false){ + LogError("[ERROR]this filter is invalid"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + throw; + } + }else + { + LogDebug("filter is NULL"); + } + + + m_onMessageReceived.attach(emitter); + EmittersMessageReceived::LockType lock = m_onMessageReceived.getLock(); + if ((m_onMessageReceived.size() == 1)&&((m_onConversationReceived.size() + m_onFolderReceived.size()) == 0)) { + m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr( + new MsgServiceHandleMgr()); + int err; + + err = msg_reg_storage_change_callback( + m_onMessageReceivedHandleMgr->getHandle(), + onMessageStorageChanged, + this); + + if (err != MSG_SUCCESS) { + LogError("Couldn't register on MMS received callback, err=" << err); + } + + m_dbusConnection->open(DBUS_BUS_SYSTEM); + } +} + +void Messaging::addOnMessageReceived( + const Api::Messaging::EmitterConversationReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, int funtionIndex) +{ + LogDebug("ENTER"); + + if(filter != NULL) + { + Try + { + LogDebug("funtionIndex = " << funtionIndex); + bool isValidFilter = validateFilter(filter, funtionIndex); + if(isValidFilter == false){ + LogError("[ERROR]this filter is invalid"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + throw; + } + }else + { + LogDebug("filter is NULL"); + } + + + m_onConversationReceived.attach(emitter); + EmittersConversationReceived::LockType lock = m_onConversationReceived.getLock(); + if ((m_onConversationReceived.size() == 1)&&((m_onMessageReceived.size() + m_onFolderReceived.size()) == 0)) { + m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr( + new MsgServiceHandleMgr()); + int err; + + err = msg_reg_storage_change_callback( + m_onMessageReceivedHandleMgr->getHandle(), + onMessageStorageChanged, + this); + + if (err != MSG_SUCCESS) { + LogError("Couldn't register on MMS received callback, err=" << err); + } + + m_dbusConnection->open(DBUS_BUS_SYSTEM); + } +} + +void Messaging::addOnMessageReceived( + const Api::Messaging::EmitterFolderReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, int funtionIndex) +{ + LogDebug("ENTER"); + + if(filter != NULL) + { + Try + { + LogDebug("funtionIndex = " << funtionIndex); + bool isValidFilter = validateFilter(filter, funtionIndex); + if(isValidFilter == false){ + LogError("[ERROR]this filter is invalid"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + throw; + } + }else + { + LogDebug("filter is NULL"); + } + + + m_onFolderReceived.attach(emitter); + EmittersFolderReceived::LockType lock = m_onFolderReceived.getLock(); + if ((m_onFolderReceived.size() == 1)&&((m_onMessageReceived.size() + m_onConversationReceived.size()) == 0)) { + m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr( + new MsgServiceHandleMgr()); + int err; + + err = msg_reg_storage_change_callback( + m_onMessageReceivedHandleMgr->getHandle(), + onMessageStorageChanged, + this); + + if (err != MSG_SUCCESS) { + LogError("Couldn't register on MMS received callback, err=" << err); + } + + m_dbusConnection->open(DBUS_BUS_SYSTEM); + } +} + +bool Messaging::validateFilter(const Api::Tizen::FilterPtr& filter, const int funtionIndex){ + LogDebug("<<<"); + + bool retBool = false; + LogDebug("funtionIndex = " << funtionIndex); + + if(filter != NULL){ + if(funtionIndex == 0) + { + Platform::Messaging::StorageChangesMessageFilterValidatorPtr validatorMsg = + Platform::Messaging::StorageChangesMessageFilterValidatorFactory::getStorageChangesMessageFilterValidator(); + + FilterValidatorPtr filterValidatorMsg = DPL::StaticPointerCast(validatorMsg); + retBool = filter->validate(filterValidatorMsg); + }else if(funtionIndex == 1) + { + Platform::Messaging::StorageChangesConversationFilterValidatorPtr validatorConv = + Platform::Messaging::StorageChangesConversationFilterValidatorFactory::getStorageChangesConversationFilterValidator(); + + FilterValidatorPtr filterValidatorConv = DPL::StaticPointerCast(validatorConv); + retBool = filter->validate(filterValidatorConv); + }else if(funtionIndex == 2) + { + Platform::Messaging::StorageChangesFolderFilterValidatorPtr validatorFolder = + Platform::Messaging::StorageChangesFolderFilterValidatorFactory::getStorageChangesFolderFilterValidator(); + + FilterValidatorPtr filterValidatorFolder = DPL::StaticPointerCast(validatorFolder); + retBool = filter->validate(filterValidatorFolder); + } + + if(retBool == false){ + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + }else{ + LogDebug("filter is NULL"); + retBool = false; + } + + LogDebug(">>> retBool:" << retBool); + return retBool; + +} + + +void Messaging::removeOnMessageMsgReceived(Api::Messaging::EmitterMessageReceived::IdType id) +{ + LogDebug("ENTER"); + m_onMessageReceived.detach(id); + EmittersMessageReceived::LockType lock = m_onMessageReceived.getLock(); + if ((m_onMessageReceived.size()+m_onConversationReceived.size()+m_onFolderReceived.size()) == 0) { + m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(NULL); + m_dbusConnection->close(); + } +} + +void Messaging::removeOnMessageConvReceived(Api::Messaging::EmitterConversationReceived::IdType id) +{ + LogDebug("ENTER"); + m_onConversationReceived.detach(id); + EmittersConversationReceived::LockType lock = m_onConversationReceived.getLock(); + if ((m_onMessageReceived.size()+m_onConversationReceived.size()+m_onFolderReceived.size()) == 0) { + m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(NULL); + m_dbusConnection->close(); + } +} + +void Messaging::removeOnMessageFolderReceived(Api::Messaging::EmitterFolderReceived::IdType id) +{ + LogDebug("ENTER"); + m_onFolderReceived.detach(id); + EmittersFolderReceived::LockType lock = m_onFolderReceived.getLock(); + if ((m_onMessageReceived.size()+m_onConversationReceived.size()+m_onFolderReceived.size()) == 0) { + m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(NULL); + m_dbusConnection->close(); + } +} + +void Messaging::OnEventReceived(const DBus::MessageEvent& event) +{ + LogDebug("ENTER"); + EventMessageReceivedPtr jsEvent(new EventMessageReceived()); + DBus::MessagePtr message = event.GetArg0(); + + + if (!message) { + jsEvent->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::PlatformException); + m_onMessageReceived.emit(jsEvent); + } else { + if (message->getInterface() == DBUS_INTERFACE_EMAIL_RECEIVED) { + int account_id = 0, mail_id = 0, thread_id = 0, status = 0; + std::string name; + emf_mailbox_t m_mailboxes; + emf_mailbox_t* mailboxes = NULL; + + DBus::Message::ReadIterator it = message->getReadIterator(); + for (int i = 0; it->isValid(); it->next(), ++i) { + if ((i == 0) && (it->getArgType() == DBUS_TYPE_INT32)) { + status = it->getInt(); + LogInfo("status: " << status); + } else if ((i == 1) && (it->getArgType() == DBUS_TYPE_INT32)) { + account_id = it->getInt(); + LogInfo("account_id: " << account_id); + } else if ((i == 2) && (it->getArgType() == DBUS_TYPE_INT32)) { + mail_id = it->getInt(); + LogInfo("mail_id: " << mail_id); + } else if ((i == 3) && (it->getArgType() == DBUS_TYPE_STRING)) { + name = it->getString(); + LogInfo("name: " << name); + } else if ((i == 4) && (it->getArgType() == DBUS_TYPE_INT32)) { + thread_id = it->getInt(); + LogInfo("thread_id: " << thread_id); + } + } + + if ((mail_id > 0) && (NOTI_MAIL_ADD == status)) + { // TODO also RECEIVE_THREAD_ITEM? + LogInfo("Email received. mail_id: " << mail_id); + + IMessagePtr msg = MessageFactory::createMessage(EMAIL, mail_id); + + // TODO Temporary fix: ignore messages from OUTBOX, SENTBOX & DRAFTBOX -> most probably we added them + Api::Messaging::FolderType folder = msg->getCurrentFolder(); + jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_ADDED); + + if (OUTBOX != folder && SENTBOX != folder && DRAFTBOX != + folder) { + IEmailPtr email = MessageFactory::convertToEmail(msg); + jsEvent->setMessage(msg); + if(m_onMessageReceived.size() == 1){ + m_onMessageReceived.emit(jsEvent); + } + + if(m_onConversationReceived.size() == 1){ + m_onConversationReceived.emit(jsEvent); + } + + } else { + LogWarning( + "New email message in ignored folder: " << folder); + } + } + else if ((mail_id > 0) && (NOTI_MAIL_DELETE == status)) + { // TODO also RECEIVE_THREAD_ITEM? + LogInfo("Email received. delete type: " << mail_id); + + std::vector strIds = String::split(name, ','); + + std::stringstream stream; + for (std::vector::iterator it = strIds.begin(); it != strIds.end(); ++it) { + LogDebug("ID is :" << *it); + + if ( (*it).length() > 0 ) //vaild id + { + stream<< *it; + int id; + stream >> id; + + IMessagePtr msg = MessageFactory::createMessage(EMAIL, id); + + Api::Messaging::FolderType folder = msg->getCurrentFolder(); + jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_DELETED); + + if (true) { // if (OUTBOX != folder && SENTBOX != folder && DRAFTBOX != folder) + IEmailPtr email = MessageFactory::convertToEmail(msg); + jsEvent->setMessage(msg); + if(m_onMessageReceived.size() == 1){ + m_onMessageReceived.emit(jsEvent); + } + if(m_onConversationReceived.size() == 1){ + m_onConversationReceived.emit(jsEvent); + } + } else { + LogWarning( + "New email message in ignored folder: " << folder); + } + } + + stream.clear(); + } //for + + } + else if ((mail_id > 0) && (NOTI_MAIL_UPDATE == status)) + { // TODO also RECEIVE_THREAD_ITEM? + LogInfo("Email received. mail_id: " << mail_id); + + IMessagePtr msg = MessageFactory::createMessage(EMAIL, mail_id); + + Api::Messaging::FolderType folder = msg->getCurrentFolder(); + jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_UPDATED); + + if (true) { // if (OUTBOX != folder && SENTBOX != folder && DRAFTBOX != folder) + IEmailPtr email = MessageFactory::convertToEmail(msg); + jsEvent->setMessage(msg); + if(m_onMessageReceived.size() == 1) + m_onMessageReceived.emit(jsEvent); + if(m_onConversationReceived.size() == 1) + m_onConversationReceived.emit(jsEvent); + } else { + LogWarning( + "New email message in ignored folder: " << folder); + } + } + else if (NOTI_MAILBOX_ADD == status) + { + LogInfo("Emailbox received. account Id: " << account_id); + LogInfo("name Id: " << name); + email_get_mailbox_by_name(account_id, name.c_str(), &mailboxes); + + m_mailboxes = *mailboxes; + + Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes)); + jsEvent->setMessageFolder(folderPtr); + jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_ADDED); + + m_onFolderReceived.emit(jsEvent); + + } + else if (NOTI_MAILBOX_UPDATE == status) + { + LogInfo("Emailbox received. account Id: " << account_id); + LogInfo("name Id: " << name); + email_get_mailbox_by_name(account_id, name.c_str(), &mailboxes); + + m_mailboxes = *mailboxes; + + Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes)); + jsEvent->setMessageFolder(folderPtr); + jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_UPDATED); + + m_onFolderReceived.emit(jsEvent); + + } + else if (NOTI_MAILBOX_DELETE == status) + { + LogInfo("Emailbox received. account Id: " << account_id); + LogInfo("name Id: " << name); + email_get_mailbox_by_name(account_id, name.c_str(), &mailboxes); + + m_mailboxes = *mailboxes; + + Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes)); + jsEvent->setMessageFolder(folderPtr); + jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_DELETED); + + m_onFolderReceived.emit(jsEvent); + + } + else + { + LogError("Couldn't retrieve message or it has been malformed."); + } + } else { + LogDebug("Wrong DBus interface, skipping it."); + } + } +} + +void Messaging::onMessageStorageChanged(MSG_HANDLE_T handle, + MSG_STORAGE_CHANGE_TYPE_T storageChangeType, + msg_message_t msg, + void* data) +{ + LogDebug("ENTER"); + Messaging* this_ = static_cast(data); + if (this_) { + Try { + int MsgType = msg_get_message_type(msg); + + if((MsgType > MSG_TYPE_INVALID) && ( MsgType <= MSG_TYPE_SMS_REJECT)) + { + if(msg_get_message_type(msg) != MSG_TYPE_MMS_NOTI) + { + IMessagePtr message = MessageFactory::createMessage( + SMS, + msg_get_message_id( + msg)); + ISmsPtr sms = MessageFactory::convertToSms(message); + IConversationPtr conversation(new Conversation(message->getId(), SMS)); + EventMessageReceivedPtr event(new EventMessageReceived()); + event->setMessage(message); + event->setConversation(conversation); + + if(storageChangeType == MSG_STORAGE_CHANGE_INSERT) + { + event->setMsg_Event_Type(EventMessageReceived::MSG_ADDED); + } + else if(storageChangeType == MSG_STORAGE_CHANGE_UPDATE) + { + event->setMsg_Event_Type(EventMessageReceived::MSG_UPDATED); + } + else if(storageChangeType == MSG_STORAGE_CHANGE_DELETE) + { + event->setMsg_Event_Type(EventMessageReceived::MSG_DELETED); + } + else if(storageChangeType == MSG_STORAGE_CHANGE_MULTIPLE) + { + event->setMsg_Event_Type(EventMessageReceived::MSG_MULTIPLE); + } + + if(this_->m_onMessageReceived.size() == 1){ + this_->m_onMessageReceived.emit(event); + } + if(this_->m_onConversationReceived.size() == 1){ + this_->m_onConversationReceived.emit(event); + } + } + else + { + LogError("Ignore this sms, this is mms noti."); + } + } + else if((MsgType >= MSG_TYPE_MMS) && (MsgType <= MSG_TYPE_MMS_NOTI)) + { + if(msg_get_message_type(msg) != MSG_TYPE_MMS_NOTI) + { + IMessagePtr message = MessageFactory::createMessage( + MMS, + msg_get_message_id( + msg)); + IMmsPtr mms = MessageFactory::convertToMms(message); + IConversationPtr conversation(new Conversation(message->getId(), MMS)); + EventMessageReceivedPtr event(new EventMessageReceived()); + event->setMessage(message); + event->setConversation(conversation); + + if(storageChangeType == MSG_STORAGE_CHANGE_INSERT) + { + event->setMsg_Event_Type(EventMessageReceived::MSG_ADDED); + } + else if(storageChangeType == MSG_STORAGE_CHANGE_UPDATE) + { + event->setMsg_Event_Type(EventMessageReceived::MSG_UPDATED); + } + else if(storageChangeType == MSG_STORAGE_CHANGE_DELETE) + { + event->setMsg_Event_Type(EventMessageReceived::MSG_DELETED); + } + else if(storageChangeType == MSG_STORAGE_CHANGE_MULTIPLE) + { + event->setMsg_Event_Type(EventMessageReceived::MSG_MULTIPLE); + } + if(this_->m_onMessageReceived.size() == 1){ + this_->m_onMessageReceived.emit(event); + } + if(this_->m_onConversationReceived.size() == 1){ + this_->m_onConversationReceived.emit(event); + } + } + else + { + LogError("Ignore this mms, this is mms noti."); + } + + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Couldn't convert message to sms."); + } + } +} + + +void Messaging::onSmsReceived(MSG_HANDLE_T handle, + msg_message_t msg, + void* data) +{ + LogDebug("ENTER"); + Messaging* this_ = static_cast(data); + if (this_) { + Try { + if(msg_get_message_type(msg) != MSG_TYPE_MMS_NOTI) + { + IMessagePtr message = MessageFactory::createMessage( + SMS, + msg_get_message_id( + msg)); + ISmsPtr sms = MessageFactory::convertToSms(message); + IConversationPtr conversation(new Conversation(message->getId(), SMS)); + + EventMessageReceivedPtr event(new EventMessageReceived()); + event->setMessage(message); + event->setConversation(conversation); + event->setMsg_Event_Type(EventMessageReceived::MSG_ADDED); + this_->m_onMessageReceived.emit(event); + } + else + { + LogError("Ignore this sms, this is mms noti."); + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Couldn't convert message to sms."); + } + } +} + +void Messaging::onMmsReceived(MSG_HANDLE_T handle, + msg_message_t msg, + void* data) +{ + LogDebug("ENTER"); + Messaging* this_ = static_cast(data); + if (this_) { + Try { + IMessagePtr message = MessageFactory::createMessage( + MMS, + msg_get_message_id( + msg)); + IMmsPtr mms = MessageFactory::convertToMms(message); + IConversationPtr conversation(new Conversation(message->getId(), MMS)); + EventMessageReceivedPtr event(new EventMessageReceived()); + event->setMessage(message); + event->setConversation(conversation); + event->setMsg_Event_Type(EventMessageReceived::MSG_ADDED); + this_->m_onMessageReceived.emit(event); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Couldn't convert message to mms."); + } + } +} + +void Messaging::getNumberOfEmails(Api::Messaging::FolderType folder, + int* read, + int* unread) +{ + LOG_ENTER + + emf_mailbox_t mailbox = {}; + mailbox.account_id = 0; // means for all accounts + mailbox.name = String::strdup( + EmailConverter::toMailboxName(folder) + ); + + int error = email_count_message(&mailbox, read, unread); + free(mailbox.name); + + if (EMF_ERROR_NONE != error) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Couldn't get number of emails. [" << error << "]"); + } + + LOG_EXIT +} + +void Messaging::getNumberOfSms(Api::Messaging::FolderType folder, + int* read, + int* unread) +{ + getNumberOfSmsMms(folder, read, unread, SMS); +} + +void Messaging::getNumberOfMms(Api::Messaging::FolderType folder, + int* read, + int* unread) +{ + getNumberOfSmsMms(folder, read, unread, MMS); +} + +void Messaging::getNumberOfSmsMms(Api::Messaging::FolderType folder, + int* read, + int* unread, + Api::Messaging::MessageType msgType) +{ + MSG_LIST_S folderListView = { 0, NULL }; + + *read = 0; + *unread = 0; + + Try + { + MSG_MESSAGE_TYPE_T msgTypePlatform; + if (SMS == msgType) { + msgTypePlatform = MSG_TYPE_SMS; + } else if (MMS == msgType) { + msgTypePlatform = MSG_TYPE_MMS; + } else { + LogError("no supported message type in this method"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + MSG_FOLDER_ID_T msgFolderId; + switch (folder) { + case INBOX: + msgFolderId = MSG_INBOX_ID; + break; + case OUTBOX: + msgFolderId = MSG_OUTBOX_ID; + break; + case SPAMBOX: + msgFolderId = MSG_SPAMBOX_ID; + break; + case SENTBOX: + msgFolderId = MSG_SENTBOX_ID; + break; + case DRAFTBOX: + msgFolderId = MSG_DRAFT_ID; + break; + default: + LogError("wrong folder type"); + Throw(WrtDeviceApis::Commons::PlatformException); + break; + } + + const MSG_SORT_RULE_S sort_rules = { MSG_SORT_BY_DISPLAY_TIME, true }; + if (msg_get_folder_view_list(MsgGetCommonHandle(), msgFolderId, + &sort_rules, + &folderListView) != MSG_SUCCESS) { + LogDebug( + "msg_get_folder_view_list empty or failed, msgFolderId=" << + (int) msgFolderId); + Throw(WrtDeviceApis::Commons::PlatformException); + } + // go thtough all message to check type of message + LogDebug("msgCount=" << (int) folderListView.nCount); + for (int msg_cnt = 0; msg_cnt < folderListView.nCount; msg_cnt++) { + LogDebug("msgMainType=" << + (int) msg_get_message_type(folderListView. + msgInfo[ + msg_cnt]) << + ", searching for = " << (int) msgTypePlatform); + if (msgTypePlatform == + msg_get_message_type(folderListView.msgInfo[ + msg_cnt])) { + if (msg_is_read(folderListView.msgInfo[msg_cnt])) + { + (*read)++; + } else { + (*unread)++; + } + } + } + msg_release_message_list(&folderListView); + + LogDebug("readed=" << *read << ", unReaded=" << *unread); + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + if (folderListView.nCount) { + msg_release_message_list(&folderListView); + } + throw; + } +} + + vector Messaging::findSms(Api::Messaging::FolderType folder, const Api::Tizen::FilterPtr& filter) + { + LogDebug("<<<"); + + vector retVal; + msg_message_t msg = msg_new_message(); + MSG_LIST_S folder_list_view = {0, NULL}; + + Try{ + const MSG_SORT_RULE_S sort_rules = {MSG_SORT_BY_DISPLAY_TIME, true}; + MSG_ERROR_T res = MSG_ERR_UNKNOWN; + const MSG_FOLDER_ID_T platformFolder = convertFolderToPlatform(folder); + res = msg_get_folder_view_list(MsgGetCommonHandle(), platformFolder, &sort_rules, &folder_list_view); + + if (MSG_SUCCESS != res) { + LogError("msg_get_folder_view_list failed " << res); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + for (int i = 0; i < folder_list_view.nCount; i++) { + if (MSG_TYPE_SMS == msg_get_message_type(folder_list_view.msgInfo[i])) { + int l_msgId = msg_get_message_id(folder_list_view.msgInfo[i]); + Api::Messaging::IMessagePtr msg = MessageFactory::createMessage(SMS, l_msgId); + + // if (!filter || !filter->isValid() || + // filter->compare(MessageFactory::convertToSms(msg))) { + retVal.push_back(msg); + // } + } + } + + msg_release_message_list(&folder_list_view); + }Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Problem with message creation, cleaning"); + if (folder_list_view.nCount) { + msg_release_message_list(&folder_list_view); + } + if (msg) { + msg_release_message(&msg); + } + throw; + } + + LogDebug(">>>"); + return retVal; + } + + vector Messaging::findMms(Api::Messaging::FolderType folder, + const Api::Tizen::FilterPtr& filter) + { + vector retVal; + msg_message_t msg = msg_new_message(); + MSG_LIST_S folder_list_view = {0, NULL}; + + Try + { + const MSG_SORT_RULE_S sort_rules = {MSG_SORT_BY_DISPLAY_TIME, true}; + MSG_ERROR_T res = MSG_ERR_UNKNOWN; + const MSG_FOLDER_ID_T platformFolder = convertFolderToPlatform(folder); + res = msg_get_folder_view_list( + MsgGetCommonHandle(), platformFolder, &sort_rules, + &folder_list_view); + + if (MSG_SUCCESS != res) { + LogError("msg_Get_folder_view_list failed" << res); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + for (int i = 0; i < folder_list_view.nCount; i++) { + if (MSG_TYPE_MMS == + msg_get_message_type(folder_list_view. + msgInfo[i])) { + int l_msgId = msg_get_message_id( + folder_list_view.msgInfo[i]); + Api::Messaging::IMessagePtr msg = MessageFactory::createMessage(MMS, l_msgId); + } + } + + msg_release_message_list(&folder_list_view); + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Problem with message creation, cleaning"); + if (folder_list_view.nCount) { + msg_release_message_list(&folder_list_view); + } + if (msg) { + msg_release_message(&msg); + } + throw; + } + + return retVal; + } + +void Messaging::createFolder(MessageType msgType, + const string& userFolder) +{ + switch (msgType) { + case Api::Messaging::SMS: + case Api::Messaging::MMS: + createMsgServiceFolder(userFolder); + break; + case Api::Messaging::EMAIL: + createEmailFolder(userFolder); + break; + default: + LogError("msg not supported"); + Throw(WrtDeviceApis::Commons::UnknownException); + } +} + +void Messaging::createMsgServiceFolder(const std::string& userFolder) +{ + if (userFolder.length() > MAX_FOLDER_NAME_SIZE) { + LogError("folder name to long"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + MSG_FOLDER_INFO_S folderInfo; + + folderInfo.folderId = 0; + strncpy(folderInfo.folderName, userFolder.c_str(), userFolder.length()); + + folderInfo.folderType = MSG_FOLDER_TYPE_USER_DEF; + + if (msg_add_folder(MsgGetCommonHandle(), &folderInfo) != MSG_SUCCESS) { + LogError("msg_add_folder failed"); + Throw(WrtDeviceApis::Commons::PlatformException); + } +} + +void Messaging::createEmailFolder(const std::string& userFolder) +{ + //TODO + LogError("TODO"); + Throw(WrtDeviceApis::Commons::UnknownException); +} + +void Messaging::deleteFolder(MessageType msgType, + const string& userFolder) +{ + switch (msgType) { + case Api::Messaging::SMS: + case Api::Messaging::MMS: + deleteMsgServiceFolder(userFolder); + break; + case Api::Messaging::EMAIL: + deleteEmailFolder(userFolder); + break; + default: + LogError("msg not supported"); + Throw(WrtDeviceApis::Commons::UnknownException); + } +} + +void Messaging::deleteMsgServiceFolder(const string& userFolder) +{ + Try + { + int platformFolderId = convertFolderToPlatform(userFolder); + if (MSG_SUCCESS != + msg_delete_folder(MsgGetCommonHandle(), platformFolderId)) { + LogError("msg_get_folder_list failed"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + throw; + } +} + +void Messaging::deleteEmailFolder(const string& userFolder) +{ + //TODO + LogError("TODO"); + Throw(WrtDeviceApis::Commons::UnknownException); +} + +vector Messaging::getFolderNames(MessageType msgType) +{ + switch (msgType) { + case Api::Messaging::SMS: + case Api::Messaging::MMS: + return getFolderNamesMsgService(); + case Api::Messaging::EMAIL: + return getFolderNamesEmail(); + default: + LogError("msg not supported"); + Throw(WrtDeviceApis::Commons::UnknownException); + } +} + +vector Messaging::getFolderNamesMsgService() +{ + vector retVal; + MSG_FOLDER_LIST_S msgFolderList = { 0, NULL }; // output data + + Try + { + if (msg_get_folder_list(MsgGetCommonHandle(), + &msgFolderList) != MSG_SUCCESS) { + LogError("msg_get_folder_list failed"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + LogDebug("number of folder=" << msgFolderList.nCount); + for (int i = 0; i < msgFolderList.nCount; i++) { + LogDebug("folderName=" << msgFolderList.folderInfo[i].folderName); + LogDebug("folderId=" << (int) msgFolderList.folderInfo[i].folderId); + LogDebug( + "folderType=" << + (int) msgFolderList.folderInfo[i].folderType); + retVal.push_back(msgFolderList.folderInfo[i].folderName); + } + (void) msg_release_folder_list(&msgFolderList); + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + if (msgFolderList.nCount) { + (void) msg_release_folder_list(&msgFolderList); + } + throw; + } + return retVal; +} + +vector Messaging::getFolderNamesEmail() +{ + vector retVal; + + string tmpStr; + emf_mailbox_t* mailboxes = NULL; + int mailboxesCount; + string emailAccountName; + Api::Messaging::EmailAccountInfo account = getCurrentEmailAccount(); + + Try + { + if (!email_get_mailbox_list(account.getIntId(), -1, &mailboxes, + &mailboxesCount) || !mailboxes) { + LogError("error during get mailboxes"); + } + for (int i = 0; i < mailboxesCount; i++) { + retVal.push_back(mailboxes->name); + LogDebug("mailbox found, name=" << mailboxes->name); + mailboxes++; + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + // nothing to clean, re-throw exception + throw; + } + + return retVal; +} + +vector Messaging::findEmail(const std::string &folder, + const Api::Tizen::FilterPtr& filter) +{ + vector retVal; + + Api::Messaging::EmailAccountInfo account = getCurrentEmailAccount(); + if (account.getId().empty()) { + LogWarning("No valid email accounts. Skipping"); + return retVal; + } + + int accountId = account.getIntId(); + + // number of found emails + int count = 0; + // start index + int startIndex = 0; + + do { + emf_mail_list_item_t* results = NULL; + int err = email_get_mail_list_ex(accountId, + folder.c_str(), + EMF_LIST_TYPE_NORMAL, + startIndex, + MESSAGE_FIND_LIMIT, + EMF_SORT_DATETIME_HIGH, + &results, + &count); + DPL::ScopedFree autoFree(results); + (void)autoFree; + if (EMF_ERROR_MAIL_NOT_FOUND == err || results == NULL) { + LogWarning("No emails found in mailbox: " << folder); + break; + } else if (EMF_ERROR_NONE != err) { + LogError( + "Unable to get mail list for mailbox: " << folder << + ", Error: " << err); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + // apply filter + for (int i = 0; i < count; ++i) { + Api::Messaging::IMessagePtr msg = MessageFactory::createMessage(EMAIL, results[i].mail_id); + + + if (!filter +// || filter->compare(MessageFactory::convertToEmail(msg)) //TODO implemnet compare in filter sangtai.kim + ) { + retVal.push_back(msg); + } + } + + startIndex += count; + } + while (count >= MESSAGE_FIND_LIMIT); + + return retVal; +} + +vector Messaging::findEmail(Api::Messaging::FolderType folder, + const Api::Tizen::FilterPtr& filter) +{ + vector result; + + Api::Messaging::EmailAccountInfo account = getCurrentEmailAccount(); + if (account.getId().empty()) { + LogWarning("No valid email accounts."); + return result; + } + + string name; + try { + name = EmailConverter::toMailboxName(folder); + } + catch (const WrtDeviceApis::Commons::PlatformException& ex) { + LogWarning(ex.DumpToString()); + return result; + } + + int accountId = account.getIntId(); + int startIndex = 0; + int count = 0; + do { + emf_mail_list_item_t* messages = NULL; + int error = email_get_mail_list_ex(accountId, + name.c_str(), + EMF_LIST_TYPE_NORMAL, + startIndex, + MESSAGE_FIND_LIMIT, + EMF_SORT_DATETIME_HIGH, + &messages, + &count); + DPL::ScopedFree freeGuard(messages); + if ((EMF_ERROR_MAIL_NOT_FOUND == error) || (NULL == messages)) { + LogWarning("No emails found in mailbox: " << name); + break; + } else if (EMF_ERROR_NONE != error) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Couldn't get mail list from mailbox: " << name << + ". [" << error << "]"); + } + + for (int i = 0; i < count; ++i) { + Api::Messaging::IMessagePtr msg = + MessageFactory::createMessage(EMAIL, messages[i].mail_id); + if (!filter +// ||filter->compare(MessageFactory::convertToEmail(msg)) //TODO implement compare in filter sangtai.kim + ) { + result.push_back(msg); + } + } + + startIndex += count; + } + while (count >= MESSAGE_FIND_LIMIT); + + return result; +} + +int Messaging::getConversationId(const int& msgId, const MessageType& msgtype) +{ + LogDebug("Enter"); + + switch(msgtype) + { + case EMAIL: + { + int index = 0, count = 0; + char *mailBox = NULL; + emf_mail_list_item_t *mailList = NULL; + + LogDebug("Current Account " << m_currentEmailAccountId); + + try + { + if (email_get_mailbox_name_by_mail_id(msgId, &mailBox) != EMF_ERROR_NONE) + { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "get mail box fail" ); + } + + if (email_get_mail_list_ex(m_currentEmailAccountId, mailBox, EMF_LIST_TYPE_NORMAL, 0, MESSAGE_FIND_LIMIT, + EMF_SORT_DATETIME_HIGH, &mailList, &count) != EMF_ERROR_NONE) + { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "get email list fail" ); + } + + if (mailBox) + free(mailBox); + + for (index = 0; index < count; index++) + { + if (mailList[index].mail_id == (int)msgId) + { + return mailList[index].thread_id; + } + } + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "can not find msg" ); + } + catch (const WrtDeviceApis::Commons::Exception& ex) + { + if (mailBox) + free(mailBox); + + LogError("Exception: " << ex.GetMessage()); + throw; + } + return MSG_ERR_INVALID_MSG_TYPE; + } + break; + case SMS: + case MMS: + { + msg_message_t msg = msg_new_message(); + MSG_SENDINGOPT_S sendOpt = {0, }; + MSG_HANDLE_T handle = MsgGetCommonHandle(); + MSG_ERROR_T err = MSG_SUCCESS; + + err = msg_get_message(handle, msgId, msg, &sendOpt); + + + if( err < MSG_SUCCESS ) + { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "can not find msg id(" << msgId << ")"); + } + + err = msg_get_ith_thread_id(msg, 0); + LogDebug(err); + if( err < MSG_SUCCESS ) + { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "can not find thread with msg id(" << msgId << ")"); + } + + return err; + } + break; + default: + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Wrong Type (" << msgId << ")"); + return MSG_ERR_INVALID_MSG_TYPE; + + } +} + +std::vector Messaging::queryConversations(const Api::Tizen::SortModePtr& sortMode, + const Api::Tizen::FilterPtr& filter, long limit, long offset) +{ + LogDebug("Enter"); + + std::vector result; + std::string filterSql; + + ConversationQueryGeneratorPtr queryGenerator(new ConversationQueryGenerator(sortMode, limit, offset)); + IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast(queryGenerator); + filter->travel(filterVisitor, 0); + + LogDebug("filterSql:[" << filterSql <<"]"); + + int conversationType = queryGenerator->getMessageType(); + switch(conversationType){ + case Api::Messaging::EMAIL:{ + LogDebug("type is EMAIL:[" << conversationType <<"]"); + queryGenerator->reset(MessageQueryGenerator::MODE_EMAIL); + filter->travel(filterVisitor, 0); + filterSql = queryGenerator->getQuery(); + result = queryEmailConversation(filterSql); + break; + } + + case Api::Messaging::SMS:{ + LogDebug("type is SMS:[" << conversationType <<"]"); + queryGenerator->reset(MessageQueryGenerator::MODE_SMS_MMS); + IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast(queryGenerator); + filter->travel(filterVisitor, 0); + filterSql = queryGenerator->getQuery(); + result = querySmsMmsConversation(filterSql); + break; + } + + case Api::Messaging::MMS:{ + LogDebug("type is MMS:[" << conversationType <<"]"); + result = querySmsMmsConversation(filterSql); + break; + } + + default:{ + LogError("[ERROR] >>> invlid type:[" << conversationType <<"]"); + return result; + } + } //switch + + return result; +} + +bool Messaging::deleteConversations(const Api::Tizen::SortModePtr& sortMode, const Api::Tizen::FilterPtr& filter) +{ + LogDebug("Enter"); + + std::vector conversationsToDelete = queryConversations(sortMode, filter); + return deleteConversations(conversationsToDelete); +} + +bool Messaging::deleteConversations(const std::vector& conversations) +{ + LogDebug("Enter"); + + if (conversations.size() == 0) + return false; + + if (conversations[0]->getType() == Api::Messaging::EMAIL) + { + LogDebug("Enter-Email"); + int threadId = 0; + + for (std::size_t i = 0; i < conversations.size(); ++i) + { + threadId = conversations[i]->getId(); + + if (email_delete_thread(threadId, false) != EMF_ERROR_NONE) + { + return false; + } + } + } + else + { + LogDebug("Enter-Msg"); + MSG_THREAD_ID_T threadId = 0; + MSG_HANDLE_T handle = MsgGetCommonHandle(); + + for (std::size_t i = 0; i < conversations.size(); ++i) + { + threadId = conversations[i]->getId(); + if (msg_delete_thread_message_list(handle, threadId) != MSG_SUCCESS) + { + return false; + } + } + } + return true; +} + +std::vector Messaging::queryFolders(const Api::Tizen::FilterPtr& filter) +{ + LogDebug("Enter"); + + emf_mailbox_t* mailboxes = NULL; + emf_mailbox_t m_mailboxes; + int mailboxesCount; + + std::vector result; + std::string folderName; + int accountId = 0; + + Api::Messaging::EmailAccountInfo account = getCurrentEmailAccount(); + + if (account.getId().empty()) { + LogWarning("No valid email accounts. Skipping"); + return result; + } + + const vector accounts = getEmailAccounts(); + + FolderQueryGeneratorPtr queryGenerator(new FolderQueryGenerator()); + + IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast(queryGenerator); + queryGenerator->reset(); + filter->travel(filterVisitor, 0); + accountId = queryGenerator->getAccountId(); + + if(accountId == 0) + { + LogWarning("No valid email accounts. accountId : 0"); + return result; + } + + if(queryGenerator->isFolderPathExist() == 1){ + folderName = queryGenerator->getFolderPath(); + + if(email_get_mailbox_by_name(accountId, folderName.c_str(), &mailboxes) != 1) + { + LogError("error during get mailboxes"); + return result; + } + + m_mailboxes = *mailboxes; + Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes)); + result.push_back(folderPtr); + + }else{ + if (!email_get_mailbox_list(accountId, -1, &mailboxes, &mailboxesCount) || !mailboxes) + { + LogError("error during get mailboxes"); + return result; + } + + if (mailboxesCount <= 0) + { + LogDebug("Empty..."); + } + else + { + for (int i = 0; i < mailboxesCount; i++) + { + + m_mailboxes = *mailboxes; + Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes)); + result.push_back(folderPtr); + mailboxes++; + } + } + } + return result; + +} + +} +} +} diff --git a/src/platform/Tizen/Messaging/Messaging.h b/src/platform/Tizen/Messaging/Messaging.h new file mode 100755 index 0000000..d06d60d --- /dev/null +++ b/src/platform/Tizen/Messaging/Messaging.h @@ -0,0 +1,238 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Messaging.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef MESSAGING_H +#define MESSAGING_H + +#include +#include +#include +#include +extern "C" { +#include +#include +} +#include +#include +#include +#include +#include +#include +#include +#include "MsgServiceHandleMgr.h" + +#include +#include +#include +#include + + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +class Messaging : public Api::Messaging::IMessaging, + private DPL::EventListener +{ + public: + static Messaging& getInstance(); + + public: + virtual ~Messaging(); + + virtual void getNumberOfMessages(Api::Messaging::MessageType msgType, + Api::Messaging::FolderType folder, + int* readed, + int* unReaded); + + virtual std::vector findMessages( + const std::vector& msgTypes, + Api::Messaging::FolderType folder, + const Api::Tizen::FilterPtr& filter); + + virtual std::vector findMessages( + const std::vector& msgTypes, + const std::string &folder, + const Api::Tizen::FilterPtr& filter); + + virtual std::vector findMessages(const Api::Tizen::FilterPtr& filter, + const Api::Tizen::SortModePtr& sortMode, const long limit, const long offset); + virtual std::vector findMessages(const Api::Tizen::FilterPtr& filter); + + virtual std::vector getMessageIds(Api::Messaging::MessageType msgType, + Api::Messaging::FolderType folder); + + virtual void createFolder(Api::Messaging::MessageType msgType, + const std::string& userFolder); + + virtual void deleteFolder(Api::Messaging::MessageType msgType, + const std::string& userFolder); + + virtual std::vector getFolderNames(Api::Messaging::MessageType msgType); + + virtual std::vector getEmailAccounts() const; + + int getEmailAccountId(const std::string& account); + + void fetchEmailHeaders(); + + static int convertFolderToPlatform(const Api::Messaging::FolderType folder); + + /** + * Gets folder id by given folder name. + * @return Folder id or 0 if not found + * @throw PlatformException on platform error. + */ + static int convertFolderToPlatform(const std::string &folder); + + void addOnMessageReceived(const Api::Messaging::EmitterMessageReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, const int funtionIndex); + + void addOnMessageReceived(const Api::Messaging::EmitterConversationReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, const int funtionIndex); + + void addOnMessageReceived(const Api::Messaging::EmitterFolderReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, const int funtionIndex); + + bool validateFilter(const Api::Tizen::FilterPtr& filter, const int funtionIndex); + + void removeOnMessageMsgReceived(Api::Messaging::EmitterMessageReceived::IdType id); + + void removeOnMessageConvReceived(Api::Messaging::EmitterConversationReceived::IdType id); + + void removeOnMessageFolderReceived(Api::Messaging::EmitterFolderReceived::IdType id); + + std::vector queryConversations(const Api::Tizen::SortModePtr& sortMode, const Api::Tizen::FilterPtr& filter, long limit=0, long offset=0); + + bool deleteConversations(const Api::Tizen::SortModePtr& sortMode, const Api::Tizen::FilterPtr& filter); + + bool deleteConversations(const std::vector& conversations); + + std::vector queryFolders(const Api::Tizen::FilterPtr& filter); + + int getConversationId(const int& msgId, const Api::Messaging::MessageType& msgType); + + private: + std::string generateFilterSql(const Api::Tizen::FilterPtr& filter); + + std::vector queryEmailConversation(const std::string& sqlWhereClause); + std::vector querySmsMmsConversation(const std::string& sqlWhereClause); + +// std::vector querySmsMmsMessages(const Api::Tizen::FilterPtr& filter, const Api::Tizen::SortModePtr& sortMode, const long limit, const long offset); + std::vector querySmsMmsMessages(const std::string& sqlWhereClause); + std::vector queryEmailMessage(const std::string& sqlWhereClause); + + std::vector createVectorFromeMessageList(const MSG_LIST_S& message_list); + std::vector createVectorFromeThreadViewList(const MSG_THREAD_VIEW_LIST_S& message_list); + + public: + static int m_currentEmailAccountId; + + static DPL::Atomic m_objCounter; + + protected: + void OnEventReceived(const DBus::MessageEvent& event); + + private: + typedef WrtDeviceApis::Commons::Emitters EmittersMessageReceived; + typedef WrtDeviceApis::Commons::Emitters EmittersConversationReceived; + typedef WrtDeviceApis::Commons::Emitters EmittersFolderReceived; + + private: + Messaging(); + + static void onMessageStorageChanged(MSG_HANDLE_T handle, + MSG_STORAGE_CHANGE_TYPE_T storageChangeType, + msg_message_t msg, + void* data); + + static void onSmsReceived(MSG_HANDLE_T handle, + msg_message_t msg, + void* data); + static void onMmsReceived(MSG_HANDLE_T handle, + msg_message_t msg, + void* data); + + private: + + void getNumberOfEmails(Api::Messaging::FolderType folder, + int* read, + int* unread); + + void getNumberOfSms(Api::Messaging::FolderType folder, + int* read, + int* unread); + + void getNumberOfMms(Api::Messaging::FolderType folder, + int* read, + int* unread); + + void getNumberOfSmsMms(Api::Messaging::FolderType folder, + int* read, + int* unread, + Api::Messaging::MessageType msgType); + + virtual std::vector findSms(Api::Messaging::FolderType folder, + const Api::Tizen::FilterPtr& filter); + + virtual std::vector findMms(Api::Messaging::FolderType folder, + const Api::Tizen::FilterPtr& filter); + + virtual std::vector findEmail(Api::Messaging::FolderType folder, + const Api::Tizen::FilterPtr& filter); + + virtual std::vector findEmail(const std::string &folder, + const Api::Tizen::FilterPtr& filter); + + std::vector getSmsIds(Api::Messaging::FolderType folder); + + std::vector getMmsIds(Api::Messaging::FolderType folder); + + std::vector getEmailIds(Api::Messaging::FolderType folder); + + void createMsgServiceFolder(const std::string& userFolder); + + void createEmailFolder(const std::string& userFolder); + + void deleteMsgServiceFolder(const std::string& userFolder); + + void deleteEmailFolder(const std::string& userFolder); + + std::vector getFolderNamesMsgService(); + + std::vector getFolderNamesEmail(); + + + void printErrorMessage(int errorCode); + + private: + EmittersMessageReceived m_onMessageReceived; + EmittersConversationReceived m_onConversationReceived; + EmittersFolderReceived m_onFolderReceived; + MsgServiceHandleMgrPtr m_onMessageReceivedHandleMgr; + DBus::ConnectionPtr m_dbusConnection; + DPL::Thread* m_dbusWorkerThread; +}; +} +} +} +#endif diff --git a/src/platform/Tizen/Messaging/MessagingService.cpp b/src/platform/Tizen/Messaging/MessagingService.cpp new file mode 100755 index 0000000..2ad93b2 --- /dev/null +++ b/src/platform/Tizen/Messaging/MessagingService.cpp @@ -0,0 +1,236 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author Wojciech Bielawski (w.bielawski@samsung.com) + */ + +#include +#include +//#include +#include +#include "MessagingService.h" +#include "MailSync.h" + +#include +#include + +using namespace DPL; +using namespace std; +using namespace TizenApis::Api::Messaging; + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +MessagingService::MessagingService() : + m_initialized(false) +{ + LogDebug("Enter"); +} + +MessagingService::~MessagingService() { + LogDebug("Leave"); + + m_opRequests.clear(); //clean Messaging Service Handles +} + +//public function. + +void MessagingService::initialize() { + LogDebug("<<<"); + m_initialized = true; + + + LogDebug(">>>"); +} + +void MessagingService::setMessagingServiceType(int type) +{ + setType(type); +} + +void MessagingService::setMessagingServiceName(const string& name) +{ + setName(name); +} + +int MessagingService::sync(const Api::Messaging::IMessagingServicePtr& messagingService, const int limit) +{ + LogDebug("<<<"); + + return MailSync::getInstance().syncAccount( messagingService, limit ); +} + +void MessagingService::syncCancel(int handle) +{ + LogDebug("<<<"); + return MailSync::getInstance().syncAccountCancel(handle); +} + +int MessagingService::syncFolder(const Api::Messaging::IMessagingServicePtr& messagingService, const std::string& folder_name, const int limit) +{ + LogDebug("<<<"); + return MailSync::getInstance().syncFolder( messagingService, folder_name, limit); +} + +void MessagingService::syncFolderCancel(int handle) +{ + LogDebug("<<<"); + return MailSync::getInstance().syncFolderCancel(handle); +} + +//operation. +int MessagingService::createOpId(int type) +{ + + int cnt = m_opRequests.size(); //item count. + int index = 0; + + if (cnt > 0) + { + //OpRequestsIterator it = std::max_element(m_opRequests.begin(), m_opRequests.end(), MessagingService::OpRequest_comparer); + OpRequestsIterator it = m_opRequests.end(); + int lastIndex = it->first; + + if ( (cnt * MESSAGING_SERVICE_OP_COUNT) >= lastIndex ) + { + index = ( lastIndex + MESSAGING_SERVICE_OP_COUNT - ( lastIndex % MESSAGING_SERVICE_OP_COUNT) ) + type; + } + else + { + int preValue = 0; + + OpRequestsIterator iter; + + for( iter = m_opRequests.begin(); iter != m_opRequests.end(); ++iter) + { + int currentValue = it->first; + + if ( currentValue - preValue > MESSAGING_SERVICE_OP_COUNT) + { + index = ( preValue + MESSAGING_SERVICE_OP_COUNT - ( preValue % MESSAGING_SERVICE_OP_COUNT) ) + type; + break; + } + else + { + index = ( currentValue + MESSAGING_SERVICE_OP_COUNT - ( currentValue % MESSAGING_SERVICE_OP_COUNT) ) + type; + } + } + + } + + } + else + { + index = type; + } + + LogDebug("m_opRequests size : " << cnt ); + LogDebug("index " << index); + m_opRequests.insert(std::make_pair(index, MessagingServiceOpData(0,type))); + + return index; +} + +int MessagingService::getHandleFromOpId(int opIdx) +{ + LogDebug("operation index size : " << opIdx); + + int handle = -1; + + OpRequestsIterator it = m_opRequests.find(opIdx); + if ( m_opRequests.end() != it) + { + handle = it->second.handle; + } + + LogDebug("index " << handle); + return handle; + +} + +Api::Messaging::IMessagePtr MessagingService::getMessageFromOpId(int opIdx) +{ + LogDebug("operation index : " << opIdx); + OpRequestsIterator it = m_opRequests.find(opIdx); + IMessagePtr msg; + if ( m_opRequests.end() != it) + { + msg = it->second.message; + } + + return msg; +} + +void MessagingService::setHandleToOpId(int opIdx, int handle) +{ + LogDebug("operation index : " << opIdx); + OpRequestsIterator it = m_opRequests.find(opIdx); + + if ( m_opRequests.end() != it) + { + LogDebug(" find Message "); + it->second.handle = handle; + } + +} + +void MessagingService::setMessageToOpId(int opIdx, Api::Messaging::IMessagePtr& message) +{ + LogDebug("operation index : " << opIdx); + OpRequestsIterator it = m_opRequests.find(opIdx); + + if ( m_opRequests.end() != it) + { + LogDebug("set Message "); + it->second.message = message; + } +} + +int MessagingService::getOpTypeFromOpId(int opIdx) +{ + LogDebug("operation index : " << opIdx); + + int type = 0; + + OpRequestsIterator it = m_opRequests.find(opIdx); + if ( m_opRequests.end() != it) + { + type = it->second.type; + } + + LogDebug("type " << type); + return type; +} + +int MessagingService::deleteOpId(int opIdx) +{ + + OpRequestsIterator it = m_opRequests.find(opIdx); + if ( m_opRequests.end() != it) + { + m_opRequests.erase(it); //delete + LogDebug("delete Request : " << m_opRequests.size()); + } + return opIdx; +} + +} +} //namespace Platform +} //namespace WrtPlugins + diff --git a/src/platform/Tizen/Messaging/MessagingService.h b/src/platform/Tizen/Messaging/MessagingService.h new file mode 100755 index 0000000..b5aef35 --- /dev/null +++ b/src/platform/Tizen/Messaging/MessagingService.h @@ -0,0 +1,106 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author + */ + +#ifndef WRTPLUGINS_PLATFORM_MESSAGING_SERVICE_H_ +#define WRTPLUGINS_PLATFORM_MESSAGING_SERVICE_H_ + +#include +#include +#include +#include + +#include +//#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +//DECLARE_GENERIC_EVENT_0(JobDoneEvent) //for manual answer (async call) +//============================================================================= +class MessagingService: + public Api::Messaging::IMessagingService +{ +public: + MessagingService(); + virtual ~MessagingService(); + //interface + //virtual void createMessage(const Api::Messaging::EventMessagingServicePtr& event); + void setMessagingServiceType(int type); + void setMessagingServiceName(const std::string& name); + + virtual int sync(const Api::Messaging::IMessagingServicePtr& messagingService, const int limit); + virtual void syncCancel(int handle); + virtual int syncFolder(const Api::Messaging::IMessagingServicePtr& messagingService, const std::string& folder_name, const int limit); + virtual void syncFolderCancel(int handle); + + int createOpId(int type); + int getHandleFromOpId(int opId); + int getOpTypeFromOpId(int opId); + Api::Messaging::IMessagePtr getMessageFromOpId(int opId); + void setHandleToOpId(int opId, int handle); + void setMessageToOpId(int opId, Api::Messaging::IMessagePtr& message); + int deleteOpId(int opId); + +protected: + //virtual void OnRequestReceived(const Api::Messaging::EventMessagingServicePtr& event); + +private: + + int create_messaging_service(); + void initialize(); + bool m_initialized; + + //EventGetMessagingServicePtr plugin_event; + + enum { + MessagingServiceManager_ERROR_NONE = 0, + MessagingServiceManager_ERROR_INVALID_PARAMETER = 1, + MessagingServiceManager_ERROR_PLATFORM_SERVICE_NOT_AVAILABLE = 2, + MessagingServiceManager_ERROR_UNKNOWN = 3, + }; + + struct MessagingServiceOpData + { + unsigned int handle; + unsigned short type; + Api::Messaging::IMessagePtr message; + + explicit MessagingServiceOpData(int handle, int type) : + handle(handle), + type(type), + message(NULL) + { + } + }; + + typedef std::map OpRequests; + typedef OpRequests::iterator OpRequestsIterator; + + OpRequests m_opRequests; // create operation + +}; + + +} +} +} +#endif /* WRTPLUGINS_PLATFORM_MESSAGING_SERVICE_H_ */ diff --git a/src/platform/Tizen/Messaging/MessagingServiceManager.cpp b/src/platform/Tizen/Messaging/MessagingServiceManager.cpp new file mode 100755 index 0000000..c47a865 --- /dev/null +++ b/src/platform/Tizen/Messaging/MessagingServiceManager.cpp @@ -0,0 +1,244 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author Wojciech Bielawski (w.bielawski@samsung.com) + */ + +#include +#include +#include +#include "MessagingServiceManager.h" +#include "MessagingService.h" + +//for email service +#include +#include + +using namespace std; +using namespace DPL; +using namespace TizenApis::Api::Messaging; + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +MessagingServiceManager::MessagingServiceManager() : + m_initialized(false), + messaging_service_handler(-1) +{ + LogDebug("Enter"); + +} + +MessagingServiceManager::~MessagingServiceManager() { + LogDebug("Leave"); +} + +std::vector MessagingServiceManager::getEmailAccounts() +{ + emf_account_t* accounts = NULL; + int count = 0; + std::vector result; + + Try { + if (email_get_account_list(&accounts, &count)) { + if (0 < count) + { + + for (int i = 0; i < count; ++i) { + LogDebug("account ID :" << accounts[i].account_id << "Name :" << accounts[i].user_name << "Addr :" << accounts[i].email_addr ); + Api::Messaging::EmailAccountInfo account(accounts[i].account_id, + accounts[i].user_name, + accounts[i].email_addr ); + result.push_back(account); + } + + if (accounts != NULL) { + email_free_account(&accounts, count); + } + + } + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + + if (accounts != NULL) { + email_free_account(&accounts, count); + } + } + + return result; +} + +//public function. +void MessagingServiceManager::getMessagingServiceManager(const EventGetMessagingServicePtr& event) { + LogDebug("<<<"); + + LogDebug("event->getAccountID():" << event->getAccountID()); + + if (m_initialized == false) { + initialize(); + } + + EventRequestReceiver::PostRequest(event); + + LogDebug(">>>"); +} + +//get the request which posted from the standard layer +void MessagingServiceManager::OnRequestReceived(const EventGetMessagingServicePtr& event) +{ + LogDebug("<<<"); + + try + { + m_messagingServices.clear(); //clear services + if (m_messagingServices.empty()) + { + //ToDo: The Message Service Code will be inserted here. + LogDebug("Message Service Type : " << event->getMessagingServiceType()); + if ( event->getMessagingServiceType() == Api::Messaging::SMS) + { + MessagingService* messagingService = new MessagingService(); + messagingService->setMessagingServiceType(Api::Messaging::SMS); + messagingService->setMessagingServiceName("SMS"); + + //ToDol: set messaging Service instance. + m_messagingServices.push_back(Api::Messaging::IMessagingServicePtr(messagingService)); + } + else if ( event->getMessagingServiceType() == Api::Messaging::MMS) + { + MessagingService* messagingService = new MessagingService(); + messagingService->setMessagingServiceType(Api::Messaging::MMS); + messagingService->setMessagingServiceName("MMS"); + + m_messagingServices.push_back(Api::Messaging::IMessagingServicePtr(messagingService)); + } + else if (event->getMessagingServiceType() == Api::Messaging::EMAIL) + { + std::vector EmailAccounts = getEmailAccounts(); + LogDebug("get Account list, size:" << EmailAccounts.size()); + + int idx = 0; + for ( idx = 0 ; idx < (int)EmailAccounts.size(); idx++) + { + LogDebug("Account ID:" << EmailAccounts[idx].getIntId() ); + + MessagingService* messagingService = NULL; + messagingService = new MessagingService(); + messagingService->setMessagingServiceType(Api::Messaging::EMAIL); + messagingService->setCurrentEmailAccount( EmailAccounts[idx] ); + + LogDebug("Account ID:" << event->getAccountID()); + if ( event->getAccountID() >= 0 ) + { + if (event->getAccountID() == EmailAccounts[idx].getIntId()) + m_messagingServices.push_back(Api::Messaging::IMessagingServicePtr(messagingService)); + else + delete messagingService; //remove service. + } + else + { + m_messagingServices.push_back(Api::Messaging::IMessagingServicePtr(messagingService)); + } + + idx++; + } + + } + + } + + event->setMessagingServicesRef(m_messagingServices); //set message services + } + catch (WrtDeviceApis::Commons::Exception &exc) + { + LogError("Exception has occurred: " << std::hex << exc.getCode()); + event->setExceptionCode(exc.getCode()); + } + + LogDebug(">>>"); +} + +// create platform's resources. For examples, it could be camera handle, location handle and so on. + +void MessagingServiceManager::initialize() { + LogDebug("<<<"); + + if (!m_initialized) { + // retVal = create_messaging_service(); + // if(retVal != MessagingServiceManager_ERROR_NONE){ + // ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Couldn't init MEssagingServiceManager module."); + // } + m_initialized = true; + } + + LogDebug(">>>"); +} + +#if 0 +void MessagingServiceManager::getEmailAccountList( vector& accounts ) +{ + LogDebug("<<<"); + + emf_account_t* emf_accounts = NULL; + int count = 0; + Try { + if (!email_get_account_list(&emf_accounts, &count)) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Couldn't get e-mail accounts."); + } + + if (0 == count) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "No e-mail account found."); + } + + for (int i = 0; i < count; ++i) { + //make email account info. + + LogDebug("account id :" << emf_accounts[i].account_id ); + LogDebug("account name :" << emf_accounts[i].user_name ); + LogDebug("account addr :" << emf_accounts[i].email_addr ); + + Api::Messaging::EmailAccountInfo account(emf_accounts[i].account_id, + emf_accounts[i].user_name, + emf_accounts[i].email_addr); + if (std::find(accounts.begin(), accounts.end(), account) == accounts.end()) { + LogDebug( "push " << emf_accounts[i].account_id << "account" ); + accounts.push_back(account); + } + } + + if (emf_accounts != NULL) { + email_free_account(&emf_accounts, count); //free + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + if (emf_accounts != NULL) { + email_free_account(&emf_accounts, count); + } + throw; + } + + LogDebug(">>>"); +} +#endif + +} +} //namespace Platform +} //namespace WrtPlugins diff --git a/src/platform/Tizen/Messaging/MessagingServiceManager.h b/src/platform/Tizen/Messaging/MessagingServiceManager.h new file mode 100755 index 0000000..1195653 --- /dev/null +++ b/src/platform/Tizen/Messaging/MessagingServiceManager.h @@ -0,0 +1,87 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author + */ + +#ifndef WRTPLUGINS_PLATFORM_MESSAGING_SERVICE_MANAGER_H_ +#define WRTPLUGINS_PLATFORM_MESSAGING_SERVICE_MANAGER_H_ + +#include +#include +#include +#include +//#include + +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +//DECLARE_GENERIC_EVENT_0(JobDoneEvent) +//============================================================================= +class MessagingServiceManager: + public Api::Messaging::IMessagingServiceManager +{ + + friend class Api::Messaging::MessagingFactory; +public: + virtual ~MessagingServiceManager(); + + //virtual void getMessagingService(const EventGetMessagingServicePtr& event); + virtual void getMessagingServiceManager (const Api::Messaging::EventGetMessagingServicePtr& event); + + static std::vector m_EmailAccounts; + +protected: + MessagingServiceManager(); + virtual void OnRequestReceived(const Api::Messaging::EventGetMessagingServicePtr& event); + +private: + +#if 0 + void getMessagingServiceAll(const Api::Messaging::EventGetMessagingServicePtr& event); + void getMessagingServiceAccount(const Api::Messaging::EventGetMessagingServicePtr& event); +#endif + + void initialize(); + int create_messaging_service(); +#if 0 + void getEmailAccountList(std::vector& accounts); +#endif + std::vector getEmailAccounts(); + + bool m_initialized; + + enum { + MessagingServiceManager_ERROR_NONE = 0, + MessagingServiceManager_ERROR_INVALID_PARAMETER = 1, + MessagingServiceManager_ERROR_PLATFORM_SERVICE_NOT_AVAILABLE = 2, + MessagingServiceManager_ERROR_UNKNOWN = 3, + }; + + int messaging_service_handler; //for test, now temporary. +}; + +} +} +} +#endif /* WRTPLUGINS_PLATFORM_MESSAGING_SERVICE_MANAGER_H_ */ diff --git a/src/platform/Tizen/Messaging/Mms.cpp b/src/platform/Tizen/Messaging/Mms.cpp new file mode 100755 index 0000000..7402654 --- /dev/null +++ b/src/platform/Tizen/Messaging/Mms.cpp @@ -0,0 +1,963 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Mms.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "Mms.h" + +#include +#include +#include +#include +#include "Messaging.h" +#include "CallbackMgr.h" +#include "MsgServiceHandleMgr.h" + +extern "C" { +#include +#include +#include +} + +namespace { +const char* TEXT_AREA = "Text"; +const char* TEXT_FILE_EXTENSION = ".txt"; +const int WHITE_COLOR = 0xffffff; +const int BLACK_COLOR = 0x000000; +const int ROOT_LAYOUT_WIDTH = 100; +const int ROOT_LAYOUT_HEIGHT = 100; +const char* EMPTY_ID = "0"; +} + +using namespace std; +using namespace TizenApis::Api::Messaging; + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +Mms::Mms(const string& id) : + IMessage(MMS, id), + m_bodyFilePath(string(tmpnam(NULL)) + TEXT_FILE_EXTENSION), + m_messageData(NULL) +{ + LogDebug("enter"); + LogDebug("m_id=" << getIdRef()); + LogDebug("m_msgType=" << getMessageType()); + if (getIdRef().empty()) { + createNewMessage(); + } else { + readExistingMessage(); + } +} + +Mms::~Mms() +{ + LogDebug("enter"); + + if (m_messageData) { + // release platform message structure + msg_release_message(&m_messageData); + } + + //remove tmp file + //trying to remove file, return value is skipped + if (!m_bodyFilePath.empty()) { + LogDebug("remove tmp file=" << m_bodyFilePath); + (void) ::remove(m_bodyFilePath.c_str()); + } +} + +void Mms::createNewMessage() +{ + if (m_messageData) { + msg_release_message(&m_messageData); + m_messageData = NULL; + } + m_messageData = msg_new_message(); + + MSG_SENDINGOPT_S sendOpt = { 0 }; + sendOpt.bSetting = false; + + // initialize platform message structure + msg_set_message_id(m_messageData, 0); // It should be set 0 + msg_set_folder_id(m_messageData, MSG_DRAFT_ID); + msg_set_message_type(m_messageData, MSG_TYPE_MMS); + msg_set_storage_id(m_messageData, MSG_STORAGE_PHONE); + msg_set_subject(m_messageData, ""); + msg_set_read_status(m_messageData, false); + msg_set_network_status(m_messageData, MSG_NETWORK_NOT_SEND); + msg_set_direction_info(m_messageData, MSG_DIRECTION_TYPE_MO); + msg_set_priority_info(m_messageData, MSG_MESSAGE_PRIORITY_NORMAL); + + tm dateT = getDateTime(); + msg_set_time(m_messageData, mktime(&dateT)); + + setMmsType(MULTIPART_MIXED); + setReadStatus(false); + setMessageStatus(Api::Messaging::MESSAGE_STATUS_DRAFT); + + LogDebug("Message created successfully, Id: " << getIdRef()); +} + +void Mms::readExistingMessage() +{ + LogDebug("entered"); + + if (getIdRef().empty() || (EMPTY_ID == getIdRef())) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Empty id."); + } + + Try { + MSG_SENDINGOPT_S option; + option.bSetting = false; + + // release old data + msg_release_message(&m_messageData); + m_messageData = NULL; + // crate new structure + m_messageData = msg_new_message(); + + // trying to get message from platform + if (MSG_SUCCESS != msg_get_message( + MsgGetCommonHandle(), convertId(getIdRef()), m_messageData, + &option)) { + LogError("get message error"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + LogDebug("message found with msgId=" << getIdRef()); + + // read all mms dat to abstraction layer + readRecipientList(m_messageData); + readPriority(m_messageData); + readSubject(m_messageData); + readBodyAndAttachments(m_messageData); + readFolder(m_messageData); + readDateTime(m_messageData); + readReadStatus(m_messageData); + } + Catch(WrtDeviceApis::Commons::Exception) { + // nothing to do + } +} + +void Mms::readDateTime(msg_message_t& messageData) +{ + tm* time = localtime(msg_get_time(messageData)); + if (!time) { + LogError("localtime failed"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + setDateTime(*time); +} + +void Mms::readReadStatus(msg_message_t& messageData) +{ + setReadStatus(msg_is_read(messageData)); +} + +void Mms::readFolder(msg_message_t& messageData) +{ + switch (msg_get_folder_id(messageData)) { + case MSG_INBOX_ID: + setFolderType(Api::Messaging::INBOX); + break; + case MSG_OUTBOX_ID: + setFolderType(Api::Messaging::OUTBOX); + break; + case MSG_SENTBOX_ID: + setFolderType(Api::Messaging::SENTBOX); + break; + case MSG_DRAFT_ID: + setFolderType(Api::Messaging::DRAFTBOX); + break; + case MSG_SPAMBOX_ID: + setFolderType(Api::Messaging::SPAMBOX); + break; + default: + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Unsupported folder id."); + } +} + +void Mms::readPriority(msg_message_t& messageData) +{ + switch (msg_get_priority_info(messageData)) { + case MSG_MESSAGE_PRIORITY_LOW: + setPriority(MessagePriority::LOW); + break; + case MSG_MESSAGE_PRIORITY_NORMAL: + setPriority(MessagePriority::NORMAL); + break; + case MSG_MESSAGE_PRIORITY_HIGH: + setPriority(MessagePriority::HIGH); + break; + default: + LogError("Wrong priority type"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Wrong priority type"); + } +} + +void Mms::readRecipientList(msg_message_t& messageData) +{ + std::string phoneNumber; + int recipientCount = msg_get_address_count(messageData); + LogDebug("Recipient count " << recipientCount); + for (int i = 0; i < recipientCount; ++i) { + int type = msg_get_direction_info(messageData); + + if (MSG_DIRECTION_TYPE_MT == type) { + phoneNumber = msg_get_ith_address(messageData, i); + if (validatePhoneNumber(phoneNumber)) { + setSourceAddress(phoneNumber); + setFrom(phoneNumber); + } + LogDebug("phone number: " << phoneNumber); + } else if (MSG_DIRECTION_TYPE_MO == type) { + switch (msg_get_ith_recipient_type(messageData, i)) { + case MSG_RECIPIENTS_TYPE_TO: + appendToRecipients(msg_get_ith_address(messageData, i)); + break; + case MSG_RECIPIENTS_TYPE_CC: + appendCcRecipients(msg_get_ith_address(messageData, i)); + break; + case MSG_RECIPIENTS_TYPE_BCC: + appendBccRecipients(msg_get_ith_address(messageData, i)); + break; + default: + LogError("Wrong type of recipient"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Wrong type of recipient"); + } + } else { + LogError("Wrong type of recipient"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Wrong type of recipient"); + } + } +} + +void Mms::readSubject(msg_message_t& messageData) +{ + setSubject(msg_get_subject(messageData)); +} + +void Mms::readBodyAndAttachments(msg_message_t& messageData) +{ + //TODO + MMS_MESSAGE_DATA_S msgBody = {}; + msg_mms_get_message_body(messageData, &msgBody); + + //if any page then multipart is related type + if (msgBody.pageCnt > 0) { + setMmsType(MULTIPART_RELATED); + } else { + setMmsType(MULTIPART_MIXED); + } + + LogDebug("page count: " << msgBody.pageCnt); + + for (int p = 0; p < msgBody.pageCnt; ++p) { + LogDebug("page " << p); + MMS_PAGE_S *page = msg_mms_get_page(p); + if (!page) { + LogError("returned page is null, continue"); + continue; + } + for (int m = 0; m < page->mediaCnt; ++m) { + LogDebug("media file " << m); + MMS_MEDIA_S* media = msg_mms_get_media(page, m); + if (!media) { + LogError("returned media is null, continue"); + continue; + } + if (0 == p && MMS_SMIL_MEDIA_TEXT == media->mediatype) { + //text value on first page goes to body attribute + LogDebug("setting body from " << media->szFilePath); + FILE* f = NULL; + f = fopen(media->szFilePath, "r"); + if (!f) { + LogError("cannot read file with body" << media->szFilePath); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Cannot read file with body"); + } + fseek(f, 0, SEEK_END); + long int size = ftell(f); + fseek(f, 0, SEEK_SET); + char* data = new (nothrow) char[size + 1]; + if (data) { + memset(data, 0, size + 1); + fread(data, 1, size, f); + setBody(data); + delete[] data; + } else { + LogError("body is not set"); + } + LogDebug("message body: '" << getBody() << "'"); + fclose(f); + } else { + LogDebug("adding attachment " << media->szFilePath); +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + IAttachmentPtr attachment = appendAttachment(media->szFilePath, + false); + //attachment->setMessage(this); //set IMessagePtr + if (NULL != media->szFileName && + strnlen(media->szFileName, MSG_FILENAME_LEN_MAX) > 0) { + LogDebug("renaming to " << media->szFileName); + attachment->rename(media->szFileName); + } else if (MMS_SMIL_MEDIA_TEXT == media->mediatype) { + std::stringstream newName; + newName << "body_page_" << p + 1 << ".txt"; + LogDebug("renaming to " << newName.str()); + attachment->rename(newName.str()); + } +#endif + } + } + } +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + + LogDebug("attachment count: " << msgBody.attachCnt); + for (int a = 0; a < msgBody.attachCnt; ++a) { + MMS_ATTACH_S* attachment = msg_mms_get_attachment(a); + if (!attachment) { + LogError("attachment is null, continue"); + continue; + } + IAttachmentPtr att = appendAttachment(attachment->szFilePath, false); + if (NULL != attachment->szFileName && + strnlen(attachment->szFileName, MSG_FILENAME_LEN_MAX) > 0) { + LogDebug("renaming to " << attachment->szFileName); + att->rename(attachment->szFileName); + } + } +#endif +} + + +void Mms::update(bool draftsOnly) +{ + LogDebug("updating m_id=" << getIdRef()); + + if (!m_messageData) { + //error if platform message not exists + LogError("message can not be updated"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + //update mms data from abstraction + if (!draftsOnly || getCurrentFolder() == Api::Messaging::DRAFTBOX) { + updateSubject(); + updateBodyAndAttachments(); + updateRecipientList(); + updatePriority(); + } + updateReadStatus(); +} + +void Mms::updatePriority() +{ + if (isPriorityValid()) { + return; + } + int priority = -1; + LogInfo("MMS updating priority"); + + //set priority in platform + switch (getPriority()) { + case MessagePriority::LOW: + priority = MSG_MESSAGE_PRIORITY_LOW; + break; + case MessagePriority::NORMAL: + priority = MSG_MESSAGE_PRIORITY_NORMAL; + break; + case MessagePriority::HIGH: + priority = MSG_MESSAGE_PRIORITY_HIGH; + break; + default: + LogError("Wrong priority"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + if (MSG_SUCCESS != + msg_set_priority_info(m_messageData, MSG_MESSAGE_PRIORITY_LOW)) { + LogError("Error during setting priority"); + Throw(WrtDeviceApis::Commons::PlatformException); + } +} + +void Mms::updateRecipientList() +{ + // check if abstraction recipient value has been changed + if (getToRecipients().isValid() && + getBccRecipients().isValid() && + getCcRecipients().isValid()) { + return; + } + + LogInfo("MMS updating platform recipients"); + + // reset addresses in platform structure + msg_reset_address(m_messageData); + + vector to = getToRecipients().getRecipients(); + vector cc = getCcRecipients().getRecipients(); + vector bcc = getBccRecipients().getRecipients(); + + // update addresses in platform structure + if (to.size()) { + LogInfo("updating to"); + for (size_t i = 0; i < to.size(); i++) { + if (msg_get_address_count(m_messageData) >= MAX_TO_ADDRESS_CNT) { + LogError("max number of recipient exceeded"); + break; + } + LogDebug("adding to[" << i << "]=" << to[i]); + if (msg_add_address(m_messageData, to[i].c_str(), + MSG_RECIPIENTS_TYPE_TO) != MSG_SUCCESS) { + LogError("problem with adding to address"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Problem with adding to address"); + } + } + } + + if (cc.size()) { + LogInfo("updating cc"); + for (size_t i = 0; i < cc.size(); i++) { + if (msg_get_address_count(m_messageData) >= MAX_TO_ADDRESS_CNT) { + LogError("max number of recipient exceeded"); + break; + } + LogDebug("adding cc[" << i << "]=" << cc[i]); + if (msg_add_address(m_messageData, cc[i].c_str(), + MSG_RECIPIENTS_TYPE_CC) != MSG_SUCCESS) { + LogError("problem with adding cc address"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Problem with adding cc address"); + } + } + } + + if (bcc.size()) { + LogInfo("updating bcc"); + for (size_t i = 0; i < bcc.size(); i++) { + if (msg_get_address_count(m_messageData) >= MAX_TO_ADDRESS_CNT) { + LogError("max number of recipient exceeded"); + break; + } + LogDebug("adding bcc[" << i << "]=" << bcc[i]); + if (msg_add_address(m_messageData, bcc[i].c_str(), + MSG_RECIPIENTS_TYPE_BCC) != MSG_SUCCESS) { + LogError("problem with adding bcc address"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "Problem with adding bcc address"); + } + } + } + + setToValidity(true); + setCcValidity(true); + setBccValidity(true); +} + +void Mms::updateSubject() +{ + // check if abstraction subject value has been changed + if (isSubjectValid()) { + return; + } + LogInfo("updating platform subject: " << getSubjectRef()); + if (MSG_SUCCESS != + msg_set_subject(m_messageData, getSubjectRef().c_str())) { + LogError("problem with setting subject"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Problem with setting subject"); + } + setSubjectValidity(true); +} + +void Mms::updateBodyAndAttachments() +{ + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + // check if attachment or body source address value has been changed + if (isAttachmentsValid() && isBodyValid()) { + return; + } +#else + if (isBodyValid()) { + return; + } +#endif + + MMS_MESSAGE_DATA_S *mmsData = NULL; + LogInfo("updating platform body and attachment"); + + Try + { + if (getMessageType() != MMS) { + LogError("Wrong msg type"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Wrong msg type"); + } + mmsData = msg_mms_create_message(); + if (!mmsData) { + LogError("create message body failed"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "create message body failed"); + } + + //body + if (!getBodyRef().empty()) { + FILE* f = NULL; + f = fopen(m_bodyFilePath.c_str(), "w"); + if (!f) { + LogError("cannot create file with body" << m_bodyFilePath); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "cannot create file with body"); + } + LogDebug("body file: " << m_bodyFilePath); + fwrite(getBodyRef().c_str(), strlen(getBodyRef().c_str()), 1, f); + + fclose(f); + if (!msg_mms_set_rootlayout(mmsData, ROOT_LAYOUT_WIDTH, + ROOT_LAYOUT_HEIGHT, WHITE_COLOR)) { + LogError("cannot create root layout"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "cannot create root layout"); + } + if (!msg_mms_add_region(mmsData, TEXT_AREA, 0, 0, ROOT_LAYOUT_WIDTH, + ROOT_LAYOUT_HEIGHT, WHITE_COLOR)) { + LogError("cannot create region"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "cannot create region"); + } + MMS_PAGE_S* page = msg_mms_add_page(mmsData, 0); + if (!page) { + LogError("cannot create page"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "cannot create page"); + } + MMS_MEDIA_S* media = msg_mms_add_media(page, + MMS_SMIL_MEDIA_TEXT, + TEXT_AREA, + const_cast( + m_bodyFilePath.c_str())); + if (!media) { + LogError("cannot create media"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "cannot create media"); + } + media->sMedia.sText.nColor = BLACK_COLOR; + media->sMedia.sText.nSize = MMS_SMIL_FONT_SIZE_NORMAL; + } + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + //attachments + struct stat buffer; + int errnum = 0; + for (size_t i = 0; i < getAttachmentsRef().size(); ++i) { + Api::Messaging::IAttachmentPtr att = getAttachment(i); + if (!att) { + continue; + } + + LogDebug("Add attachment=" << att->getFullPath()); + //checking file + errnum = stat(att->getFullPath().c_str(), &buffer); + if (errnum) { + LogError("Opening file: " << + att->getFullPath().c_str() << + " " << strerror(errnum)); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "cannot open attachment file"); + } + + //this function should return valid pointer + if (!msg_mms_add_attachment(mmsData, + const_cast(att->getFullPath(). + c_str()))) { + LogError("add attachment failed"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "add attachment failed"); + } + LogDebug("Attachment added"); + + //reset errno + errnum = 0; + } + +#endif + if (MSG_SUCCESS != msg_mms_set_message_body(m_messageData, mmsData)) { + LogError("set message body error"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "set message body error"); + } + + msg_mms_destroy_message(mmsData); +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + setAttachmentsValidity(true); +#endif + setBodyValidity(true); + + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Platform error"); + if (mmsData) { + msg_mms_destroy_message(mmsData); + } + throw; + } + + +} + + +void Mms::updateReadStatus() +{ + if (isReadStatusValid()) { + return; + } + + LogInfo("updating platform read status: " << isRead()); + if (MSG_SUCCESS != msg_set_read_status(m_messageData, isRead())) { + LogError("problem with setting subject"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Problem with setting subject"); + } + + setReadStatusValidity(true); +} + +void Mms::updateIsRead() +{ + LogDebug("updating m_id=" << getIdRef()); + + if (!m_messageData) { + //error if platform message not exists + LogError("message can not be updated"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + // check if abstraction from m_isReadChange value has been changed + if (isReadChangeStatusValid()) { + // do not update if not changed + return; + } + + Try + { + if (this->getIdRef().empty()) { + LogError("existing msgId is zero, remove msg not done"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "existing msgId is zero, remove msg not done"); + } + + if (MSG_SUCCESS != + msg_update_read_status(MsgGetCommonHandle(), convertId(getIdRef()), isReadChangeStatus())) + { + LogError("Failed to update isRead"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Failed to update isRead"); + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("platform error occurs"); + } + setisReadChangeStatusValidity(true); + +} + +void Mms::readAllData() +{ + readExistingMessage(); +} + +void Mms::moveToFolder(const FolderType newFolder) +{ + update(); + + Try + { + MSG_FOLDER_ID_T platfromFolderId = Messaging::convertFolderToPlatform( + newFolder); + + if (msg_move_msg_to_folder(MsgGetCommonHandle(), convertId(getId()), + platfromFolderId) != MSG_SUCCESS) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Error during movinf message"); + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("remove message error"); + throw; + } +} + +void Mms::moveToFolder(const string& newFolder) +{ + update(); + + Try + { + MSG_FOLDER_ID_T platfromFolderId = Messaging::convertFolderToPlatform( + newFolder); + + if (msg_move_msg_to_folder(MsgGetCommonHandle(), convertId(getId()), + platfromFolderId) != MSG_SUCCESS) { + LogError("msg_move_msg_to_folder error"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "msg_move_msg_to_folder error"); + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("remove message error"); + throw; + } +} + +void Mms::copyToFolder(const FolderType newFolder) +{ + update(); + + msg_message_t msg = msg_new_message(); + + Try + { + MSG_SENDINGOPT_S option = { false, false, false }; + option.option.smsSendOpt.bReplyPath = true; + if (MSG_SUCCESS == + msg_get_message(MsgGetCommonHandle(), convertId(getIdRef()), msg, + &option)) { + const MSG_FOLDER_ID_T platfromFolderId = + Messaging::convertFolderToPlatform(newFolder); + msg_set_message_id(msg, 0); + msg_set_folder_id(msg, platfromFolderId); + + int error = msg_add_message(MsgGetCommonHandle(), msg, &option); + if (error != MSG_SUCCESS) { + LogError("msg_add_message failed, error code=" << error); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "msg_add_message failed"); + } + } + if (msg) { + msg_release_message(&msg); + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("remove message error"); + if (msg) { + msg_release_message(&msg); + } + throw; + } +} + +void Mms::copyToFolder(const string& newFolder) +{ + update(); + + msg_message_t msg = msg_new_message(); + + Try + { + MSG_SENDINGOPT_S option = { false, false, false }; + option.option.smsSendOpt.bReplyPath = true; + if (MSG_SUCCESS == + msg_get_message(MsgGetCommonHandle(), convertId(getIdRef()), msg, + &option)) { + const MSG_FOLDER_ID_T platfromFolderId = + Messaging::convertFolderToPlatform(newFolder); + msg_set_message_id(msg, 0); + msg_set_folder_id(msg, platfromFolderId); + + int error = msg_add_message(MsgGetCommonHandle(), msg, &option); + if (error != MSG_SUCCESS) { + LogError("msg_add_message failed, error code=" << error); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "msg_add_message failed"); + } + } + if (msg) { + msg_release_message(&msg); + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("remove message error"); + if (msg) { + msg_release_message(&msg); + } + throw; + } +} + +void Mms::remove() +{ + LogDebug("delete m_id=" << getIdRef()); + + Try + { + if (this->getIdRef().empty()) { + LogError("existing msgId is zero, remove msg not done"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "existing msgId is zero, remove msg not done"); + } + + if (MSG_SUCCESS != + msg_delete_message(MsgGetCommonHandle(), + convertId(getIdRef()))) { + LogError("Failed to delete Message"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Failed to delete Message"); + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("platform error occurs"); + } +} + +int Mms::send() +{ + LogDebug("sending message, id=" << getIdRef()); + Try + { + //prepare for sending sms/mms + update(); + + LogDebug("Start Sending Message..."); + LogDebug("msgId=" << msg_get_message_id(m_messageData)); + LogDebug("subject: " << msg_get_subject(m_messageData)); + LogDebug("recipient count: " << msg_get_address_count(m_messageData)); + LogDebug("body size : " << msg_get_message_body_size( m_messageData )); + + for (int i = 0; i < msg_get_address_count(m_messageData); ++i) { + LogDebug("recipient[" << i << "]: " << + msg_get_ith_address(m_messageData, i)); + } + + LogDebug("trying to send mms"); + MSG_ERROR_T err = CallbackMgrSingleton::Instance().registerAndSend( + msg_mms_send_message, + m_messageData, + this); + + if (err != MSG_SUCCESS) { + LogError("Sending Message (submit request) failed!!! err=" << err); + setMessageStatus(MESSAGE_STATUS_FAILED); + goto ERROR; + } + + setMessageStatus(MESSAGE_STATUS_SENDING); + + LogDebug("Sending Message request is submitted!"); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("message is not send, manually run callback"); + goto ERROR; + } + + return 0; +ERROR: + ReqReceiverMessage *requestReceiver = getRequestReceiver(); + if (requestReceiver) { + LogError("send Error"); + EventSendMessagePtr event = getSendMessageEvent(); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + requestReceiver->WrtDeviceApis::Commons::EventRequestReceiver< EventSendMessage >::ManualAnswer(event); + } + +} + +void Mms::sendingCallback(MSG_SENT_STATUS_S *sent_status) +{ + LogInfo( + "sendingCallback callback received. Req id = " << + sent_status->reqId << " Status = " << (int)sent_status->status); + if (MSG_NETWORK_SEND_SUCCESS == sent_status->status) { + LogDebug("sending ok"); + setSendingStatusOk(); + setMessageStatus(MESSAGE_STATUS_SENT); + } else { + LogError("sending failed: " << + static_cast(sent_status->status)); + setSendingStatusFailed(); + setMessageStatus(MESSAGE_STATUS_FAILED); + } +} + +void Mms::sendCancel(int handle) +{ + LogDebug("sending message, id=" << getIdRef()); + //#warning "TODO" + LogDebug("handle =" << handle); +} + +void Mms::setSendingStatusOk() +{ + //success callback should be executed here + ReqReceiverMessage *requestReceiver = getRequestReceiver(); + if (requestReceiver) { + LogInfo("calling JS success callback"); + EventSendMessagePtr event = getSendMessageEvent(); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::None); + + for ( int index=0; index < msg_get_address_count(m_messageData); index++) + { + LogDebug( "Address :" << msg_get_ith_address(m_messageData, index)); + event->m_successRecipients.push_back(msg_get_ith_address(m_messageData, index)); + } + + requestReceiver->WrtDeviceApis::Commons::EventRequestReceiver< EventSendMessage >::ManualAnswer(event); + + } +} + +void Mms::setSendingStatusFailed() +{ + //error callback should be executed here + EventOnSendingFailedEmitterPtr emitter = getEmitter(); + if (emitter) { + EventOnSendingFailedPtr event(new EventOnSendingFailed); + event->setError(EventOnSendingFailed::UNKNOWN); // TODO error codes + emitter->emit(event); + } else { + ReqReceiverMessage *requestReceiver = getRequestReceiver(); + if (requestReceiver) { + LogError("calling JS error callback"); + EventSendMessagePtr event = getSendMessageEvent(); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + + for ( int index=0; index < msg_get_address_count(m_messageData); index++) + { + LogDebug( "Address :" << msg_get_ith_address(m_messageData, index)); + event->m_failRecipients.push_back(msg_get_ith_address(m_messageData, index)); + } + + } + } +} + +Api::Messaging::FolderType Mms::toFolder(const std::string &folder) +{ + if (folder == "INBOX") { + return INBOX; + } else if (folder == "OUTBOX") { + return OUTBOX; + } else if (folder == "SENTBOX") { + return SENTBOX; + } else if (folder == "DRAFTBOX") { + return DRAFTBOX; + } + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Invalid folder"); +} +} +} +} diff --git a/src/platform/Tizen/Messaging/Mms.h b/src/platform/Tizen/Messaging/Mms.h new file mode 100755 index 0000000..d41ad16 --- /dev/null +++ b/src/platform/Tizen/Messaging/Mms.h @@ -0,0 +1,123 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Mms.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef MMS_H +#define MMS_H + +#include +#include +#include "MmsSlide.h" +#include "ISendingObserver.h" + +extern "C" { +#include +#include +} + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +class Mms : public Api::Messaging::IMms, + public ISendingObserver, + public Api::Messaging::MmsSlides +{ + public: + explicit Mms(const std::string& id = ""); + + ~Mms(); + + // implementation of interface of IMessage class + virtual void update(bool draftsOnly = false); + + virtual void readAllData(); + + virtual void moveToFolder(const Api::Messaging::FolderType newFolder); + + virtual void moveToFolder(const std::string& newFolder); + + virtual void copyToFolder(const Api::Messaging::FolderType newFolder); + + virtual void copyToFolder(const std::string& newFolder); + + virtual void remove(); + + virtual int send(); + + virtual void sendingCallback(MSG_SENT_STATUS_S *sent_status); + + virtual void sendCancel(int handle); + + void setSendingStatusOk(); + + void setSendingStatusFailed(); + + static Api::Messaging::FolderType toFolder(const std::string &folder); + + private: + + void updatePriority(); + + void updateRecipientList(); + + void updateSubject(); + + void updateBodyAndAttachments(); + + void updateReadStatus(); + + void updateIsRead(); + + void readPriority(msg_message_t& messageData); + + void readRecipientList(msg_message_t& messageData); + + void readSubject(msg_message_t& messageData); + + void readBodyAndAttachments(msg_message_t& messageData); + + void readFolder(msg_message_t& messageData); + + void readDateTime(msg_message_t& messageData); + + void readReadStatus(msg_message_t& messageData); + + void createNewMessage(); + + void readExistingMessage(); + + private: + + std::string m_bodyFilePath; + + msg_message_t m_messageData; +}; + +typedef DPL::SharedPtr MmsPtr; +} +} +} +#endif diff --git a/src/platform/Tizen/Messaging/MmsSlide.cpp b/src/platform/Tizen/Messaging/MmsSlide.cpp new file mode 100755 index 0000000..88a4ff2 --- /dev/null +++ b/src/platform/Tizen/Messaging/MmsSlide.cpp @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file MmsSlide.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ diff --git a/src/platform/Tizen/Messaging/MmsSlide.h b/src/platform/Tizen/Messaging/MmsSlide.h new file mode 100755 index 0000000..a81281a --- /dev/null +++ b/src/platform/Tizen/Messaging/MmsSlide.h @@ -0,0 +1,46 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file MmsSlide.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef TIZEN_MMS_SLIDE_H +#define TIZEN_MMS_SLIDE_H + +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +class MmsSlide : + public virtual Api::Messaging::IMmsSlide, + public Api::Messaging::MmsSlide +{ +}; +} +} +} +#endif + diff --git a/src/platform/Tizen/Messaging/MsgServiceHandleMgr.h b/src/platform/Tizen/Messaging/MsgServiceHandleMgr.h new file mode 100755 index 0000000..ce27c2e --- /dev/null +++ b/src/platform/Tizen/Messaging/MsgServiceHandleMgr.h @@ -0,0 +1,116 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file CallbackMgr.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef MSGSERVICEHANDLEMGR_H +#define MSGSERVICEHANDLEMGR_H + +#include +#include +#include +#include +#include + +extern "C" { +#include +} + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +/* + * Class used for msg service handle manager + */ +class MsgServiceHandleMgr +{ + public: + MsgServiceHandleMgr() : m_msgHandle(NULL) + { + LogInfo("enter"); + // open one handle per all messaging + if (MSG_SUCCESS != msg_open_msg_handle(&m_msgHandle)) { + LogError("Unable to open handle"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + } + + public: + ~MsgServiceHandleMgr() + { + LogInfo("enter"); + if (!!m_msgHandle) { + msg_close_msg_handle(&m_msgHandle); + } + } + + MSG_HANDLE_T getHandle() const + { + if (!m_msgHandle) { + LogError("Messaging handle not initialized"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + return m_msgHandle; + } + + private: + MSG_HANDLE_T m_msgHandle; +}; + +typedef DPL::SharedPtr MsgServiceHandleMgrPtr; +typedef DPL::ThreadLocalVariable TlvMsgServiceHandleMgr; + +class MsgServiceHandle +{ + protected: + MsgServiceHandle() + { + } + + public: + ~MsgServiceHandle() + { + } + + MSG_HANDLE_T getHandle() + { + if (m_tlvHandleMgr.IsNull()) { + m_tlvHandleMgr = MsgServiceHandleMgrPtr(new MsgServiceHandleMgr()); + } + return (*m_tlvHandleMgr)->getHandle(); + } + + private: + TlvMsgServiceHandleMgr m_tlvHandleMgr; +}; + +typedef DPL::Singleton MsgServiceHandleSingleton; + +#define MsgGetCommonHandle() MsgServiceHandleSingleton::Instance().getHandle() +} +} +} +#endif /* MSGSERVICEHANDLEMGR_H */ + diff --git a/src/platform/Tizen/Messaging/NetworkStatus.cpp b/src/platform/Tizen/Messaging/NetworkStatus.cpp new file mode 100755 index 0000000..436aab8 --- /dev/null +++ b/src/platform/Tizen/Messaging/NetworkStatus.cpp @@ -0,0 +1,89 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include +#include +#include "NetworkStatus.h" + +namespace { +const char* DBUS_INTERFACE_NETWORK_STATUS = "User.Email.NetworkStatus"; +const int DBUS_MESSAGE_PARAMETERS_NUMBER = 5; +} + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +NetworkStatus::NetworkStatus(const DBus::MessagePtr& message) +{ + Assert(message->getInterface() == DBUS_INTERFACE_NETWORK_STATUS); + initialize(message); +} + +int NetworkStatus::getStatus() const +{ + return m_status; +} + +int NetworkStatus::getAccountId() const +{ + return m_accountId; +} + +std::string NetworkStatus::getSource() const +{ + return m_source; +} + +int NetworkStatus::getMailId() const +{ + return m_mailId; +} + +int NetworkStatus::getErrorCode() const +{ + return m_errorCode; +} + +void NetworkStatus::initialize(const DBus::MessagePtr& message) +{ + DBus::Message::ReadIterator it = message->getReadIterator(); + for (int i = 0; i < DBUS_MESSAGE_PARAMETERS_NUMBER; it->next(), ++i) { + if (!it->isValid()) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Missing some properties."); + } + + switch (i) { + case 0: m_status = it->getInt(); + break; + case 1: m_accountId = it->getInt(); + break; + case 2: m_source = it->getString(); + break; + case 3: m_mailId = it->getInt(); + break; + case 4: m_errorCode = it->getInt(); + break; + } + } +} +} +} +} diff --git a/src/platform/Tizen/Messaging/NetworkStatus.h b/src/platform/Tizen/Messaging/NetworkStatus.h new file mode 100755 index 0000000..5d804d2 --- /dev/null +++ b/src/platform/Tizen/Messaging/NetworkStatus.h @@ -0,0 +1,64 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef NETWORKSTATUS_H_ +#define NETWORKSTATUS_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +class NetworkStatus : private DPL::Noncopyable +{ + public: + explicit NetworkStatus(const DBus::MessagePtr& message); + + int getStatus() const; + int getAccountId() const; + std::string getSource() const; + int getMailId() const; + int getErrorCode() const; + + private: + void initialize(const DBus::MessagePtr& message); + + private: + int m_status; + int m_accountId; + /* + * Not sure what it stores. According to source code of Email application + * it can contain string "ACTIVESYNC" or name of the file which stores body. + */ + std::string m_source; + int m_mailId; + int m_errorCode; +}; + +typedef DPL::SharedPtr NetworkStatusPtr; +} +} +} + +#endif // NETWORKSTATUS_H_ diff --git a/src/platform/Tizen/Messaging/ScopedMail.h b/src/platform/Tizen/Messaging/ScopedMail.h new file mode 100755 index 0000000..4cb36fd --- /dev/null +++ b/src/platform/Tizen/Messaging/ScopedMail.h @@ -0,0 +1,60 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef TIZEN_MESSAGING_SCOPEDMAIL_H_ +#define TIZEN_MESSAGING_SCOPEDMAIL_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +struct ScopedMailPolicy +{ + typedef emf_mail_t* Type; + + static Type NullValue() + { + LogDebug("NullValue"); + return NULL; + } + + static void Destroy(Type mail) + { + LogDebug("Destroy"); + if (NullValue() != mail) { + LogDebug("email_free_mail"); + int error = email_free_mail(&mail, 1); + if (EMF_ERROR_NONE != error) { + LogError("Failed to destroy mail: " << error); + } + } + } +}; + +typedef DPL::ScopedPtr ScopedMail; +} +} +} +#endif diff --git a/src/platform/Tizen/Messaging/ScopedMailbox.h b/src/platform/Tizen/Messaging/ScopedMailbox.h new file mode 100755 index 0000000..b8e760d --- /dev/null +++ b/src/platform/Tizen/Messaging/ScopedMailbox.h @@ -0,0 +1,60 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef TIZEN_MESSAGING_SCOPEDMAILBOX_H_ +#define TIZEN_MESSAGING_SCOPEDMAILBOX_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +struct ScopedMailboxPolicy +{ + typedef emf_mailbox_t* Type; + + static Type NullValue() + { + LogDebug("NullValue"); + return NULL; + } + + static void Destroy(Type mailbox) + { + LogDebug("Destroy"); + if (NullValue() != mailbox) { + LogDebug("email_free_mailbox"); + int error = email_free_mailbox(&mailbox, 1); + if (EMF_ERROR_NONE != error) { + LogError("Failed to destroy mailbox: " << error); + } + } + } +}; + +typedef DPL::ScopedPtr ScopedMailbox; +} +} +} +#endif diff --git a/src/platform/Tizen/Messaging/Sms.cpp b/src/platform/Tizen/Messaging/Sms.cpp new file mode 100755 index 0000000..c6fbc0c --- /dev/null +++ b/src/platform/Tizen/Messaging/Sms.cpp @@ -0,0 +1,698 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Sms.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include "Sms.h" +#include +#include +#include +#include "Messaging.h" +#include "CallbackMgr.h" +#include "MsgServiceHandleMgr.h" + +extern "C" { +#include +#include +} + +using namespace std; +using namespace TizenApis::Api::Messaging; + +namespace { +const char* EMPTY_ID = "0"; +} + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +Sms::Sms(const string& id) : + IMessage(SMS, id), + m_messageData(NULL) +{ + LogDebug("enter"); + LogDebug("m_id=" << getIdRef()); + LogDebug("m_msgType=" << getMessageType()); + + if (getIdRef().empty()) { + createNewMessage(); + } else { + readExistingMessage(); + } + + Touch(); +} + +Sms::~Sms() +{ + LogDebug("enter"); + + if (m_messageData) { + // release platform message structure + msg_release_message(&m_messageData); + } +} + +void Sms::update(bool draftsOnly) +{ + LogDebug("updating m_id=" << getIdRef()); + + if (!m_messageData) { + //error if platform message not exists + LogError("message can not be updated"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + //update all sms data + if (!draftsOnly || getCurrentFolder() == Api::Messaging::DRAFTBOX) { + updateBody(); + updateFrom(); + updateTo(); + updateSourceAddress(); + } + updateReadStatus(); +} + +void Sms::readAllData() +{ + readExistingMessage(); +} + +void Sms::moveToFolder(const FolderType newFolder) +{ + update(); + + Try + { + const MSG_FOLDER_ID_T platfromFolderId = + Messaging::convertFolderToPlatform(newFolder); + + //call platform api to move message to other folder + if (msg_move_msg_to_folder(MsgGetCommonHandle(), convertId(getId()), + platfromFolderId) != MSG_SUCCESS) { + Throw(WrtDeviceApis::Commons::PlatformException); + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("remove message error"); + throw; + } +} + +void Sms::moveToFolder(const std::string& newFolder) +{ + update(); + //TODO +} + +void Sms::copyToFolder(const FolderType newFolder) +{ + update(); + + msg_message_t msg = msg_new_message(); + + Try + { + MSG_SENDINGOPT_S option = { false, false, false }; + option.option.smsSendOpt.bReplyPath = true; + // trying to get message from platform + if (MSG_SUCCESS == + msg_get_message(MsgGetCommonHandle(), convertId(getIdRef()), msg, + &option)) { + const MSG_FOLDER_ID_T platfromFolderId = + Messaging::convertFolderToPlatform(newFolder); + // new id will me set (initialize to 0) + msg_set_message_id(msg, 0); + msg_set_folder_id(msg, platfromFolderId); + + // trying to add message + int error = msg_add_message(MsgGetCommonHandle(), msg, &option); + if (error != MSG_SUCCESS) { + LogError("msg_add_message failed, error code=" << error); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + //releasing platform message structure + msg_release_message(&msg); + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("remove message error"); + if (msg) { + //releasing platform message structure + msg_release_message(&msg); + } + throw; + } +} + +void Sms::copyToFolder(const std::string& newFolder) +{ + update(); + //TODO +} + +int Sms::send() +{ + LogDebug("sending message, id=" << getIdRef()); + + //prepare for sending sms + update(); + + // split the message + LogDebug("Start Sending Message..."); + LogDebug("msgId=" << msg_get_message_id(m_messageData)); + LogDebug("subject: " << msg_get_subject(m_messageData)); + LogDebug("recipient count: " << msg_get_address_count(m_messageData)); + + SendRequest req; + + for (int i = 0; i < msg_get_address_count(m_messageData); ++i) { + if (MSG_RECIPIENTS_TYPE_TO != + msg_get_ith_recipient_type(m_messageData, i)) { + continue; + } + msg_message_t msg = createNewCopyOfPLatformMsg(m_messageData); + + // remove all addresses except ith + msg_reset_address(msg); + const char* to = msg_get_ith_address(m_messageData, i); + msg_add_address(msg, to, MSG_RECIPIENTS_TYPE_TO); + + setMessageStatus(MESSAGE_STATUS_SENDING); + + LogDebug("recipient: " << msg_get_ith_address(msg, 0)); + LogDebug("body: " << msg_sms_get_message_body(msg)); + + req.queue.push(msg); + } + + DPL::Mutex::ScopedLock lock(&m_mutex); + m_sendRequests.push(req); + + // schedule sending + PostEvent(0); + + LogDebug("sending method finished"); + + return 0; //sms handle is -1; +} + +void Sms::sendingCallback(MSG_SENT_STATUS_S *sent_status) +{ + LogInfo( + "sendingCallback callback received. Req id = " << + sent_status->reqId << " Status = " << (int)sent_status->status << + ", Recipient=" << getRecipient()); + + DPL::Mutex::ScopedLock lock(&m_mutex); + + if (sent_status->status != MSG_NETWORK_SEND_SUCCESS) { + m_sendRequests.front().failed = true; // TODO mutex + //send callback, error for recipient + setSendingStatusFailed(getRecipient()); + setMessageStatus(MESSAGE_STATUS_FAILED); + } else { + setSendingStatusOk(getRecipient()); + setMessageStatus(MESSAGE_STATUS_SENT); + } + + msg_release_message(¤tQueue().front()); + currentQueue().pop(); + + //schedule another sub message send + PostEvent(0); +} + +void Sms::OnEventReceived(const int&) +{ + LogDebug("enter"); + // send another one + sendSubMessage(); +} + +Api::Messaging::FolderType Sms::toFolder(const std::string &folder) +{ + if (folder == "INBOX") { + return INBOX; + } else if (folder == "OUTBOX") { + return OUTBOX; + } else if (folder == "SENTBOX") { + return SENTBOX; + } else if (folder == "DRAFTBOX") { + return DRAFTBOX; + } + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Invalid folder"); +} + +void Sms::sendSubMessage() +{ + LogDebug("enter"); + + DPL::Mutex::ScopedLock lock(&m_mutex); + + // if current request queue gets empty, try next one + while (!m_sendRequests.empty()) { + // send as long as the sending fails until there are no more messages + for (MSG_ERROR_T err = MSG_ERR_UNKNOWN; + err != MSG_SUCCESS && !currentQueue().empty(); + ) { + err = CallbackMgrSingleton::Instance().registerAndSend( + msg_sms_send_message, + currentQueue().front(), + this); + LogInfo("Sending Message (submit request) result:" << err); + if (err != MSG_SUCCESS) { + LogError( + "Sending Message (submit request) failed!!! err=" << err); + msg_release_message(¤tQueue().front()); + currentQueue().pop(); + m_sendRequests.front().failed = true; + //send callback, error for recipient + setSendingStatusFailed(getRecipient()); + } + } + + // empty queue -> notify about results + if (currentQueue().empty()) { + /* + if (m_sendRequests.front().failed) { + setSendingStatusFailed(); + } else { + setSendingStatusOk(); + } + */ + // this request is finished, try next one + m_sendRequests.pop(); + continue; + } + break; + } +} + +void Sms::setSendingStatusOk(const string &recipient) +{ + LogDebug("enter, success number is : " << recipient); + //success callback should be executed here + ReqReceiverMessage *requestReceiver = getRequestReceiver(); + if (requestReceiver) { + EventSendMessagePtr event = getSendMessageEvent(); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::None); + event->m_successRecipients.push_back(recipient); + //LogDebug("total address size : " << msg_get_address_count(m_messageData) << " Status size : " << event->m_successRecipients.size() + event->m_failRecipients.size()); + if ( event->m_successRecipients.size() + event->m_failRecipients.size() == msg_get_address_count(m_messageData)) + { + requestReceiver->WrtDeviceApis::Commons::EventRequestReceiver< EventSendMessage >::ManualAnswer(event); + } + } +} + +void Sms::setSendingStatusFailed(const string &recipient) +{ + LogDebug("enter, fail number is : " << recipient); + //error callback should be executed here + EventOnSendingFailedEmitterPtr emitter = getEmitter(); + if (emitter) { + EventOnSendingFailedPtr event(new EventOnSendingFailed); + event->setError(EventOnSendingFailed::UNKNOWN); // TODO error codes + emitter->emit(event); + } else { + ReqReceiverMessage *requestReceiver = getRequestReceiver(); + if (requestReceiver) { + LogError("calling JS error callback"); + EventSendMessagePtr event = getSendMessageEvent(); + event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException); + event->m_failRecipients.push_back(recipient); + //LogDebug("total address size : " << msg_get_address_count(m_messageData) << " Status size : " << event->m_successRecipients.size() + event->m_failRecipients.size()); + if ( event->m_successRecipients.size() + event->m_failRecipients.size() == msg_get_address_count(m_messageData)) + { + requestReceiver->WrtDeviceApis::Commons::EventRequestReceiver< EventSendMessage >::ManualAnswer(event); + } + } + } +} + +void Sms::remove() +{ + Try + { + // delete message from platform + if (msg_delete_message(MsgGetCommonHandle(), + convertId(getId())) != MSG_SUCCESS) { + LogError("delete message failed"); + Throw(WrtDeviceApis::Commons::PlatformException); + } else { + LogDebug("message deleted succesfully"); + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("remove message error"); + throw; + } +} + +void Sms::createNewMessage() +{ + if (m_messageData) { + // release platform message if it was created previously + msg_release_message(&m_messageData); + m_messageData = NULL; + } + // create new platform message + m_messageData = msg_new_message(); + Try + { + MSG_SENDINGOPT_S option = { false, false, false }; + option.option.smsSendOpt.bReplyPath = true; + + //default message initialization + msg_set_message_id(m_messageData, 0); // It should be set 0 + msg_set_folder_id(m_messageData, MSG_DRAFT_ID); + msg_set_message_type(m_messageData, MSG_TYPE_SMS); + msg_set_storage_id(m_messageData, MSG_STORAGE_PHONE); + msg_set_network_status(m_messageData, MSG_NETWORK_NOT_SEND); + + // update sms data + updateBody(); + updateTo(); + + setMessageStatus(Api::Messaging::MESSAGE_STATUS_DRAFT); + + tm dateT = getDateTime(); + msg_set_time(m_messageData, mktime(&dateT)); + + LogDebug("Message created successfully, msgId=" << getId()); + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Problem with message creation, cleaning"); + } +} + +void Sms::readExistingMessage() +{ + if (getIdRef().empty() || (EMPTY_ID == getIdRef())) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Empty id."); + } + + Try { + MSG_SENDINGOPT_S option = { false, false, false }; + option.option.smsSendOpt.bReplyPath = true; + + // release old data + msg_release_message(&m_messageData); + m_messageData = NULL; + // create new platform structure + m_messageData = msg_new_message(); + + MSG_MESSAGE_ID_T l_id = convertId(getIdRef()); + LogDebug("reading message id=" << l_id); + // trying to get message from platform + if (MSG_SUCCESS == + msg_get_message(MsgGetCommonHandle(), l_id, m_messageData, + &option)) { + LogDebug("message found with msgId=" << getIdRef()); + + // read all mms dat to abstraction layer + readRecipientList(m_messageData); + readBody(m_messageData); + readFolder(m_messageData); + readDateTime(m_messageData); + readReadStatus(m_messageData); + readSize(m_messageData); + } else { + LogError("message not found with msgId=" << getIdRef()); + setId(""); + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + // nothing to do + } +} + +void Sms::updateBody() +{ + // check if abstraction body value has been changed + if (isBodyValid()) { + return; + } + LogInfo("updating platfoprm body"); + + // change body value in platform structure + msg_sms_set_message_body(m_messageData, getBodyRef().c_str(), + getBodyRef().length()); + + // set flag as true - platform synchronized with abstraction + setBodyValidity(true); +} + +void Sms::updateTo() +{ + // check if abstraction recipient (to) value has been changed + if (getToRecipients().isValid()) { + return; + } + LogInfo("updating platform to"); + + // change recipient value in platform structure + msg_reset_address(m_messageData); + vector to = getToRecipients().getRecipients(); + LogInfo("updating to"); + for (size_t i = 0; i < to.size(); i++) { + if (i >= MAX_TO_ADDRESS_CNT) { + LogError("max number of recipient exceeded"); + break; + } + LogDebug("adding to[" << i << "]=" << to[i]); + string tmpAddr = to[i]; + // function for validating phone number + if (validatePhoneNumber(tmpAddr)) { + // add phone number to platform message struncture + if (msg_add_address(m_messageData, tmpAddr.c_str(), + MSG_RECIPIENTS_TYPE_TO) != MSG_SUCCESS) { + LogError("problem witgh add address"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + } else { + //nothing to do if wrong format + LogError("wrong phone number format"); + + } + } + + // set flag as true - platform synchronized with abstraction + setToValidity(true); +} + +void Sms::updateFrom() +{ + // check if abstraction from field value has been changed + if (getFromValidity()) { + // do not update if not changed + return; + } + LogInfo("updating platform from"); + + //TODO + + // set flag as true - platform synchronized with abstraction + setFromValidity(true); +} + +void Sms::updateSourceAddress() +{ + // check if abstraction source address value has been changed + if (getSourceAddressValidity()) { + // do not update if not changed + return; + } + LogInfo("updating platform source address"); + + //TODO + + // set flag as true - platform synchronized with abstraction + setSourceAddressValidity(true); +} + +void Sms::updateReadStatus() +{ + LogInfo("updating platform read status: " << isRead()); + if (isReadStatusValid()) { + // do not update if not changed + return; + } + + if (MSG_SUCCESS != msg_set_read_status(m_messageData, isRead())) { + LogError("problem with setting subject"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Problem with setting subject"); + } + setReadStatusValidity(true); +} + +void Sms::updateIsRead() +{ + LogDebug("updating m_id=" << getIdRef()); + + if (!m_messageData) { + //error if platform message not exists + LogError("message can not be updated"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + + // check if abstraction from m_isReadChange value has been changed + if (isReadChangeStatusValid()) { + // do not update if not changed + return; + } + + Try + { + if (this->getIdRef().empty()) { + LogError("existing msgId is zero, remove msg not done"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, + "existing msgId is zero, remove msg not done"); + } + + if (MSG_SUCCESS != + msg_update_read_status(MsgGetCommonHandle(), convertId(getIdRef()), isReadChangeStatus())) + { + LogError("Failed to update isRead"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Failed to update isRead"); + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("platform error occurs"); + } + setisReadChangeStatusValidity(true); + +} + + +void Sms::readRecipientList(msg_message_t& messageData) +{ + LogDebug("Adding recipients to message, count=" << + msg_get_address_count(messageData)); + // iterate for all address and store in abstraction + for (int i = 0; i < msg_get_address_count(messageData); i++) { + string tmp = msg_get_ith_address(messageData, i); + int type = msg_get_direction_info(messageData); + + if (MSG_DIRECTION_TYPE_MT == type) { + if (validatePhoneNumber(tmp)) { + setSourceAddress(tmp); + setFrom(tmp); + } + } else if (MSG_DIRECTION_TYPE_MO == type) { + appendToRecipients(tmp); + } else { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Wrong type of recipient."); + } + } +} + +void Sms::readBody(msg_message_t& messageData) +{ + //set abstraction body value + setBody(msg_sms_get_message_body(messageData)); +} + +void Sms::readFolder(msg_message_t& messageData) +{ + switch (msg_get_folder_id(messageData)) { + case MSG_INBOX_ID: + setFolderType(Api::Messaging::INBOX); + break; + case MSG_OUTBOX_ID: + setFolderType(Api::Messaging::OUTBOX); + break; + case MSG_SENTBOX_ID: + setFolderType(Api::Messaging::SENTBOX); + break; + case MSG_DRAFT_ID: + setFolderType(Api::Messaging::DRAFTBOX); + break; + case MSG_SPAMBOX_ID: + setFolderType(Api::Messaging::SPAMBOX); + break; + default: + LogError("Wrong folder id"); + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Unsupported folder id."); + } +} + +void Sms::readDateTime(msg_message_t& messageData) +{ + tm* time = localtime(msg_get_time(messageData)); + if (!time) { + LogError("localtime failed"); + Throw(WrtDeviceApis::Commons::PlatformException); + } + setDateTime(*time); +} + +void Sms::readReadStatus(msg_message_t& messageData) +{ + // get read status + setReadStatus(msg_is_read(messageData)); +} + +void Sms::readSize(msg_message_t& messageData) +{ + setSize(msg_get_message_body_size(messageData)); +} + +msg_message_t Sms::createNewCopyOfPLatformMsg(const msg_message_t src) const +{ + msg_message_t msg = msg_new_message(); + + msg_set_message_id(msg, 0); + msg_set_storage_id(msg, msg_get_storage_id(src)); + msg_set_message_type(msg, msg_get_message_type(src)); + msg_set_folder_id(msg, msg_get_folder_id(src)); + for (int i = 0; i < msg_get_address_count(src); i++) { + msg_add_address(msg, msg_get_ith_address(src, + i), + msg_get_ith_recipient_type(src, i)); + } + msg_sms_set_message_body(msg, msg_sms_get_message_body( + src), msg_get_message_body_size(src)); + msg_set_subject(msg, msg_get_subject(src)); + msg_set_time(msg, *msg_get_time(src)); + msg_set_network_status(msg, msg_get_network_status(src)); + msg_set_encode_type(msg, msg_get_encode_type(src)); + msg_set_read_status(msg, msg_is_read(src)); + msg_set_protect_status(msg, msg_is_protected(src)); + msg_set_priority_info(msg, msg_get_priority_info(src)); + msg_set_direction_info(msg, msg_get_direction_info(src)); + msg_set_port(msg, msg_get_dest_port(src), msg_get_src_port(src)); + msg_set_scheduled_time(msg, *msg_get_scheduled_time(src)); + + return msg; +} +} +} +} diff --git a/src/platform/Tizen/Messaging/Sms.h b/src/platform/Tizen/Messaging/Sms.h new file mode 100755 index 0000000..cee75ad --- /dev/null +++ b/src/platform/Tizen/Messaging/Sms.h @@ -0,0 +1,141 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file Sms.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef SMS_H +#define SMS_H + +#include +#include "ISendingObserver.h" +#include + +extern "C" { +#include +#include +} + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +class Sms : public Api::Messaging::ISms, + public ISendingObserver, + public DPL::Controller::Type > +{ + public: + explicit Sms(const std::string& id = ""); + + virtual ~Sms(); + + // implementation of interface of IMessage class + virtual void update(bool draftsOnly = false); + + virtual void readAllData(); + + virtual void moveToFolder(const Api::Messaging::FolderType newFolder); + + virtual void moveToFolder(const std::string& newFolder); + + virtual void copyToFolder(const Api::Messaging::FolderType newFolder); + + virtual void copyToFolder(const std::string& newFolder); + + virtual void remove(); + + virtual int send(); + + virtual void sendCancel(int handle) + { + } + + virtual void sendingCallback(MSG_SENT_STATUS_S *sent_status); + + virtual void OnEventReceived(const int& /*event*/); + + static Api::Messaging::FolderType toFolder(const std::string &folder); + + private: + void sendSubMessage(); + + void setSendingStatusOk(const std::string &recipient = std::string()); + + void setSendingStatusFailed(const std::string &recipient = std::string()); + + void createNewMessage(); + + void readExistingMessage(); + + void updateBody(); + + void updateTo(); + + void updateFrom(); + + void updateSourceAddress(); + + void updateReadStatus(); + + void updateIsRead(); + + void readRecipientList(msg_message_t& messageData); + + void readBody(msg_message_t& messageData); + + void readFolder(msg_message_t& messageData); + + void readDateTime(msg_message_t& messageData); + + void readReadStatus(msg_message_t& messageData); + + void readSize(msg_message_t& messageData); + + std::queue& currentQueue() + { + return m_sendRequests.front().queue; + } + + msg_message_t createNewCopyOfPLatformMsg(const msg_message_t src) const; + + private: + msg_message_t m_messageData; + bool m_sendingFailed; + DPL::Mutex m_mutex; + + struct SendRequest + { + // queue of sub messages for each recipient + std::queue queue; + bool failed; + + SendRequest() : failed(false) + { + } + }; + // queue of send requests + std::queue m_sendRequests; +}; +} +} +} +#endif diff --git a/src/platform/Tizen/Messaging/SyncNetworkStatus.cpp b/src/platform/Tizen/Messaging/SyncNetworkStatus.cpp new file mode 100755 index 0000000..4f1714d --- /dev/null +++ b/src/platform/Tizen/Messaging/SyncNetworkStatus.cpp @@ -0,0 +1,95 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include +#include +#include "SyncNetworkStatus.h" +#include + +namespace { +const char* DBUS_INTERFACE_NETWORK_STATUS = "User.Email.NetworkStatus"; +const int DBUS_MESSAGE_PARAMETERS_NUMBER = 5; +} + +namespace TizenApis { +namespace Platform { +namespace Messaging { + +SyncNetworkStatus::SyncNetworkStatus(const DBus::MessagePtr& message) +{ + Assert(message->getInterface() == DBUS_INTERFACE_NETWORK_STATUS); + initialize(message); +} + +int SyncNetworkStatus::getStatus() const +{ + return m_status; +} + +int SyncNetworkStatus::getHandle() const +{ + return m_handle; +} + +std::string SyncNetworkStatus::getSource() const +{ + return m_source; +} + +int SyncNetworkStatus::getMailId() const +{ + return m_mailId; +} + +int SyncNetworkStatus::getErrorCode() const +{ + return m_errorCode; +} + +void SyncNetworkStatus::initialize(const DBus::MessagePtr& message) +{ + DBus::Message::ReadIterator it = message->getReadIterator(); + for (int i = 0; i < DBUS_MESSAGE_PARAMETERS_NUMBER; it->next(), ++i) { + if (!it->isValid()) { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Missing some properties."); + } + + switch (i) { + case 0: m_status = it->getInt(); + LogDebug("status :" << m_status); + break; + case 1: m_mailId = it->getInt(); + LogDebug("mail ID :" << m_mailId); + break; + case 2: m_source = it->getString(); + LogDebug("source :" << m_source); + break; + case 3: m_handle = it->getInt(); + LogDebug("handle :" << m_handle); + break; + case 4: m_errorCode = it->getInt(); + LogDebug("error Code :" << m_errorCode); + break; + } + } +} +} +} +} diff --git a/src/platform/Tizen/Messaging/SyncNetworkStatus.h b/src/platform/Tizen/Messaging/SyncNetworkStatus.h new file mode 100755 index 0000000..b16dfe4 --- /dev/null +++ b/src/platform/Tizen/Messaging/SyncNetworkStatus.h @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef SYNCNETWORKSTATUS_H_ +#define SYNCNETWORKSTATUS_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Messaging { +class SyncNetworkStatus : private DPL::Noncopyable +{ + public: + explicit SyncNetworkStatus(const DBus::MessagePtr& message); + + int getStatus() const; + int getHandle() const; + std::string getSource() const; + int getMailId() const; + int getErrorCode() const; + + private: + void initialize(const DBus::MessagePtr& message); + + private: + int m_status; + int m_handle; + /* + * Not sure what it stores. According to source code of Email application + * it can contain string "ACTIVESYNC" or name of the file which stores body. + */ + std::string m_source; + int m_mailId; + int m_errorCode; +}; + +typedef DPL::SharedPtr SyncNetworkStatusPtr; +} +} +} +#endif // SYNCNETWORKSTATUS_H_ \ No newline at end of file diff --git a/src/platform/Tizen/Messaging/config.cmake b/src/platform/Tizen/Messaging/config.cmake new file mode 100755 index 0000000..d014587 --- /dev/null +++ b/src/platform/Tizen/Messaging/config.cmake @@ -0,0 +1,72 @@ +get_current_path() + +pkg_search_module(msg-service-module REQUIRED msg-service) +pkg_search_module(email-service-module REQUIRED email-service) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_MESSAGING + ${msg-service-module_INCLUDE_DIRS} + ${email-service-module_INCLUDE_DIRS} + ${INCLUDES_PLATFORM_IMPLEMENTATION_DBUS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_MESSAGING + ${msg-service-module_LIBRARIES} + ${email-service-module_LIBRARIES} + ${LIBS_PLATFORM_IMPLEMENTATION_DBUS} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_MESSAGING + ${CURRENT_PATH}/MessagingServiceManager.cpp + ${CURRENT_PATH}/MessagingService.cpp + + # ${CURRENT_PATH}/Attachment.cpp + ${CURRENT_PATH}/BinarySms.cpp + ${CURRENT_PATH}/Email.cpp + ${CURRENT_PATH}/Messaging.cpp + ${CURRENT_PATH}/Mms.cpp + ${CURRENT_PATH}/Sms.cpp + ${CURRENT_PATH}/CallbackMgr.cpp + ${CURRENT_PATH}/NetworkStatus.cpp + ${CURRENT_PATH}/SyncNetworkStatus.cpp + ${CURRENT_PATH}/MailSender.cpp + ${CURRENT_PATH}/MailSync.cpp + ${CURRENT_PATH}/EmailService.cpp + ${CURRENT_PATH}/EmailUtils.cpp + ${CURRENT_PATH}/EmailConverter.cpp + ${CURRENT_PATH}/MessageQueryGenerator.cpp + ${CURRENT_PATH}/Conversation.cpp + ${CURRENT_PATH}/MessageFolder.cpp + ${CURRENT_PATH}/ConversationQueryGenerator.cpp + ${CURRENT_PATH}/FolderQueryGenerator.cpp + ${CURRENT_PATH}/messageDB/MsgSqliteWrapper.cpp + ${CURRENT_PATH}/messageDB/MessageStorageReader.cpp + # ${CURRENT_PATH}/../../API/Filesystem/IManager.cpp + # ${CURRENT_PATH}/../../API/Filesystem/IPath.cpp + # ${CURRENT_PATH}/../../API/Filesystem/INode.cpp + # ${CURRENT_PATH}/../../API/Filesystem/IStream.cpp + # ${CURRENT_PATH}/../../API/Filesystem/EventCopy.cpp + # ${CURRENT_PATH}/../../API/Filesystem/EventFind.cpp + # ${CURRENT_PATH}/../../API/Filesystem/EventResolve.cpp + # ${CURRENT_PATH}/../../API/Filesystem/EventMove.cpp + # ${CURRENT_PATH}/../../API/Filesystem/EventRemove.cpp + # ${CURRENT_PATH}/../../API/Filesystem/EventOpen.cpp + # ${CURRENT_PATH}/../../API/Filesystem/EventListNodes.cpp + # ${CURRENT_PATH}/../../API/Filesystem/EventReadText.cpp + # ${CURRENT_PATH}/../../API/Filesystem/NodeFilter.cpp + # ${CURRENT_PATH}/../../API/Filesystem/PathUtils.cpp + # ${CURRENT_PATH}/../Filesystem/System.cpp + # ${CURRENT_PATH}/../Filesystem/Manager.cpp + # ${CURRENT_PATH}/../Filesystem/Utils.cpp + # ${CURRENT_PATH}/../Filesystem/Path.cpp + # ${CURRENT_PATH}/../Filesystem/Node.cpp + # ${CURRENT_PATH}/../Filesystem/Stream.cpp + # ${CURRENT_PATH}/../Filesystem/NodeFilterMatcher.cpp + # ${CURRENT_PATH}/../Filesystem/Command.cpp + # ${CURRENT_PATH}/../Filesystem/MoveCommand.cpp + # ${CURRENT_PATH}/../Filesystem/RemoveCommand.cpp + # ${CURRENT_PATH}/../Filesystem/CopyCommand.cpp + ${SRCS_PLATFORM_IMPLEMENTATION_DBUS} + PARENT_SCOPE +) diff --git a/src/platform/Tizen/Messaging/messageDB/MessageStorageReader.cpp b/src/platform/Tizen/Messaging/messageDB/MessageStorageReader.cpp new file mode 100755 index 0000000..eb653b5 --- /dev/null +++ b/src/platform/Tizen/Messaging/messageDB/MessageStorageReader.cpp @@ -0,0 +1,434 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * MessageStorageReader.cpp + * + * Created on: 2011. 11. 16. + * Author: sangtai + */ + +#include "MessageStorageReader.h" +#include "MsgSqliteWrapper.h" + +#include + +namespace{ +//TODO copied from MsgInternalTypes.h + typedef unsigned char MSG_MAIN_TYPE_T; + typedef unsigned char MSG_SUB_TYPE_T; + typedef unsigned char MSG_CLASS_TYPE_T; + + typedef struct{ + MSG_MAIN_TYPE_T mainType; /**< Message main type. See enum _MSG_MAIN_TYPE_E */ + MSG_SUB_TYPE_T subType; /**< Message sub type. See enum _MSG_SUB_TYPE_E */ + MSG_CLASS_TYPE_T classType; /**< Message class type. See enum _MSG_CLASS_TYPE_E */ + } MSG_MESSAGE_TYPE_S; + + typedef struct{ + MSG_MESSAGE_ID_T msgId; /**< Indicates the message ID of this message. */ + MSG_FOLDER_ID_T folderId; /**< Indicates the folder ID. see enum _MSG_FOLDER_TYPE_E */ + MSG_REFERENCE_ID_T referenceId; /**< Indicates group message of messages that is sent together. */ + MSG_MESSAGE_TYPE_S msgType; /**< Indicates the message type either of SMS or MMS */ + MSG_STORAGE_ID_T storageId; /**< Indicates where the message is saved. see enum _MSG_FOLDER_TYPE_E*/ + int nAddressCnt; /**< Indicates the count of addresses. */ + MSG_ADDRESS_INFO_S addressList[MAX_TO_ADDRESS_CNT]; /**< Indicates the address information list. */ + char replyAddress[MAX_PHONE_NUMBER_LEN+1]; /**< Indicates the reply address. */ + char subject[MAX_SUBJECT_LEN+1]; /**< Indicates the message subject. */ + time_t displayTime; /**< Indicates the display time related to the specific operation. */ + time_t scheduledTime; /**< Indicates the time to send scheduled message. */ + MSG_NETWORK_STATUS_T networkStatus; /**< Indicates the network status of the message. */ + MSG_ENCODE_TYPE_T encodeType; /**< Indicates the string encoding type. */ + bool bRead; /**< Indicates whether the message is read or not. */ + bool bProtected; /**< Indicates whether the message is protected or not. */ + bool bBackup; /**< Indicates whether the message was restored from PC. */ + MSG_PRIORITY_TYPE_T priority; /**< Indicates the priority of the message. */ + MSG_DIRECTION_TYPE_T direction; /**< Indicates whether the message is MO or MT, affecting address. */ + MSG_PORT_INFO_S msgPort; /**< Indicates the port number information. */ + int attachCount; /**< Indicates the count of attached files in mms. */ + char thumbPath[MSG_FILEPATH_LEN_MAX+1]; + size_t dataSize; /**< Indicates the data size. The unit is byte. */ + void *pData; /**< Indicates the message payload information as a body. default character encoding is UTF-8*/ + void *pMmsData; /**< Indicates the message payload information as a body. default character encoding is UTF-8*/ + } MSG_MESSAGE_S; + + typedef struct + { + MSG_THREAD_ID_T threadId; /**< Indicates the thread ID of this peer. */ + char threadAddr[MAX_THREAD_ADDR_LEN+1]; /**< Indicates the address of this peer. > */ + char threadName[MAX_THREAD_NAME_LEN+1]; /**< Indicates the name of this peer. > */ + char threadImagePath[MAX_IMAGE_PATH_LEN+1]; /**< Indicates the image path of this peer */ + MSG_MESSAGE_TYPE_S threadType; /**< Indicates the latest msg type. */ + char threadData[MAX_THREAD_DATA_LEN+1]; /**< Indicates the latest msg data. */ + time_t threadTime; /**< Indicates the latest msg time. */ + MSG_DIRECTION_TYPE_T direction; /**< Indicates whether the message is MO or MT (affecting address). */ + + MSG_CONTACT_ID_T contactId; /**< Indicates the unique contact ID. */ + + int unreadCnt; /**< Indicates the unread messages from the Peer. */ + int smsCnt; /**< Indicates the SMS messages from the Peer. */ + int mmsCnt; /**< Indicates the MMS messages from the Peer. */ + } MSG_THREAD_VIEW_S; + + enum _MSG_MAIN_TYPE_E + { + MSG_UNKNOWN_TYPE = 0, /**< Unknown main type */ + MSG_SMS_TYPE, /**< SMS */ + MSG_MMS_TYPE, /**< MMS */ + }; +}//namespace + +enum _MSG_SUB_TYPE_E +{ + /* SMS Specific Message Type */ + MSG_NORMAL_SMS = 0, /**< Text SMS message */ + MSG_CB_SMS, /**< Cell Broadcasting message */ + MSG_JAVACB_SMS, /**< JAVA Cell Broadcasting message */ + MSG_TYPE0_SMS, /**< Short Message Type 0 */ + MSG_REPLACE_TYPE1_SMS, /**< Replace Short Message Type 1 */ + MSG_REPLACE_TYPE2_SMS, /**< Replace Short Message Type 2 */ + MSG_REPLACE_TYPE3_SMS, /**< Replace Short Message Type 3 */ + MSG_REPLACE_TYPE4_SMS, /**< Replace Short Message Type 4 */ + MSG_REPLACE_TYPE5_SMS, /**< Replace Short Message Type 5 */ + MSG_REPLACE_TYPE6_SMS, /**< Replace Short Message Type 6 */ + MSG_REPLACE_TYPE7_SMS, /**< Replace Short Message Type 7 */ + MSG_WAP_SI_SMS, /**< WAP Push Message SI */ + MSG_WAP_SL_SMS, /**< WAP Push Message SL */ + MSG_WAP_CO_SMS, /**< WAP Push Message CO */ + MSG_MWI_VOICE_SMS, /**< MWI Message Voice */ + MSG_MWI_FAX_SMS, /**< MWI Message Fax */ + MSG_MWI_EMAIL_SMS, /**< MWI Message Email */ + MSG_MWI_OTHER_SMS, /**< MWI Message Other */ + MSG_STATUS_REPORT_SMS, /**< SMS-STATUS-REPORT */ + MSG_SYNCML_CP, /**< SyncML Message CP */ + MSG_LBS_SMS, /**< LBS Message */ + MSG_SOS_SMS, /**< SOS Message */ + MSG_REJECT_SMS, /**< Reject Message */ + MSG_CONCAT_SIM_SMS, /**< Concatenated Message in SIM */ + + /* MMS Specific Message Type */ + MSG_SENDREQ_MMS = 24, /**< MMS Send Request message */ + MSG_SENDCONF_MMS, /**< MMS Send Confirm message */ + MSG_NOTIFICATIONIND_MMS, /**< MMS Notification Indication message */ + MSG_GET_MMS, /**< MMS GET MMS message */ + MSG_NOTIFYRESPIND_MMS, /**< MMS Notify Response Indication message */ + MSG_RETRIEVE_MMS, /**< MMS Retrive MMS message */ + MSG_RETRIEVE_AUTOCONF_MMS, /**< MMS Retrieve Confirm message by auto retrieving*/ + MSG_RETRIEVE_MANUALCONF_MMS, /**< MMS Retrieve Confirm message by manual retrieving*/ + MSG_ACKNOWLEGEIND_MMS, /**< MMS Acknowledge Indication message */ + MSG_DELIVERYIND_MMS, /**< MMS Delivery Indication message */ + MSG_READRECIND_MMS, /**< MMS Read Receive Indication message */ + MSG_READORGIND_MMS, /**< MMS Read Origin Indication message */ + MSG_FORWARD_MMS, /**< MMS Forward message */ + MSG_FORWARDREQ_MMS, /**< MMS Forward Request message */ + MSG_FORWARDCONF_MMS, /**< MMS Forward Confirm message */ + MSG_READREPLY_MMS, /**< MMS Read Reply message */ + MSG_SENDREQ_JAVA_MMS, /**< MMS Send Request message for JAVA MMS */ +}; + + +MessageStorageReader::MessageStorageReader() { + // TODO Auto-generated constructor stub + +} + +MessageStorageReader::~MessageStorageReader() { + // TODO Auto-generated destructor stub +} + +MSG_ERROR_T MessageStorageReader::MsgStoConnectDB(){ + return MSG_SUCCESS; +} + +MSG_ERROR_T MessageStorageReader::MsgStoDisconnectDB(){ + if (dbHandle.disconnect() != MSG_SUCCESS){ + LogError(">>>[ERROR] DB Disconnect Fail"); + return MSG_ERR_DB_DISCONNECT; + } + + LogDebug(">>>"); + + return MSG_SUCCESS; +} + +int MessageStorageReader::queryMessage(const std::string& whereClause, /*out*/MSG_LIST_S *pMsgFolderViewList){ + LogDebug("<<< whereClause:[" << whereClause << "]"); + + if (pMsgFolderViewList == NULL){ + LogDebug("pMsgFolderViewList is NULL"); + return MSG_ERR_NULL_POINTER; + } + + int rowCnt = 0; + int index = 27; // numbers of index + + unsigned int addrId = 0; + + std::ostringstream oStream; + std::string stringSqlQuery; + char firstName[MAX_DISPLAY_NAME_LEN]; + char lastName[MAX_DISPLAY_NAME_LEN]; + char displayName[MAX_DISPLAY_NAME_LEN]; + + std::string tmpWhereClause; + if(whereClause.length()==0){ + tmpWhereClause.append("WHERE "); + }else{ + tmpWhereClause.append(whereClause); + tmpWhereClause.append(" "); + tmpWhereClause.append("AND "); + } + + tmpWhereClause.append("(A.ADDRESS_ID = B.ADDRESS_ID)"); + + LogDebug("<<< tmpWhereClause:[" << tmpWhereClause << "]"); + + oStream << "SELECT A.MSG_ID, A.ADDRESS_ID, A.FOLDER_ID, A.REFERENCE_ID, A.STORAGE_ID, A.MAIN_TYPE, A.SUB_TYPE, \ +A.DISPLAY_TIME, A.DATA_SIZE, A.NETWORK_STATUS, A.READ_STATUS, A.PROTECTED, A.BACKUP, A.PRIORITY, \ +A.MSG_DIRECTION, A.SCHEDULED_TIME, A.SUBJECT, A.MSG_TEXT, B.ADDRESS_TYPE, B.RECIPIENT_TYPE, \ +B.CONTACT_ID, B.ADDRESS_VAL, B.DISPLAY_NAME, B.FIRST_NAME, B.LAST_NAME, A.ATTACHMENT_COUNT, A.THUMB_PATH \ +FROM " << MSGFW_MESSAGE_TABLE_NAME << " A, " << MSGFW_ADDRESS_TABLE_NAME << " B "; + + oStream << tmpWhereClause; + stringSqlQuery = oStream.str(); + + LogDebug("stringSqlQuery:[" << stringSqlQuery << "]"); + MSG_ERROR_T err = dbHandle.getTable(stringSqlQuery.c_str(), &rowCnt); + if (err == MSG_ERR_DB_NORECORD){ + LogDebug("MSG_ERR_DB_NORECORD"); + pMsgFolderViewList->nCount = 0; + pMsgFolderViewList->msgInfo = NULL; + dbHandle.freeTable(); + LogDebug(">>> MSG_ERR_DB_NORECORD"); + return MSG_SUCCESS; + }else if ( err != MSG_SUCCESS ){ + dbHandle.freeTable(); + return err; + } + + pMsgFolderViewList->nCount = rowCnt; + LogDebug("pMsgCommInfoList->nCount [" << pMsgFolderViewList->nCount << "]"); + + pMsgFolderViewList->msgInfo = (msg_message_t*)new char[sizeof(MSG_MESSAGE_S*)*rowCnt]; + + MSG_MESSAGE_S* pTmp = NULL; + for (int i = 0; i < rowCnt; i++){ + pMsgFolderViewList->msgInfo[i] = (msg_message_t)new char[sizeof(MSG_MESSAGE_S)]; + pTmp = (MSG_MESSAGE_S*)pMsgFolderViewList->msgInfo[i]; + memset(pTmp, 0x00, sizeof(pTmp)); + + pTmp->pData = NULL; + pTmp->pMmsData = NULL; + + pTmp->msgId = dbHandle.getColumnToInt(index++); + addrId = dbHandle.getColumnToInt(index++); + pTmp->folderId = dbHandle.getColumnToInt(index++); + pTmp->referenceId = dbHandle.getColumnToInt(index++); + pTmp->storageId = dbHandle.getColumnToInt(index++); + pTmp->msgType.mainType = dbHandle.getColumnToInt(index++); + pTmp->msgType.subType = dbHandle.getColumnToInt(index++); + pTmp->displayTime = (time_t)dbHandle.getColumnToInt(index++); + pTmp->dataSize = dbHandle.getColumnToInt(index++); + pTmp->networkStatus = dbHandle.getColumnToInt(index++); + pTmp->bRead = dbHandle.getColumnToInt(index++); + pTmp->bProtected = dbHandle.getColumnToInt(index++); + pTmp->bBackup = dbHandle.getColumnToInt(index++); + pTmp->priority = dbHandle.getColumnToInt(index++); + pTmp->direction= dbHandle.getColumnToInt(index++); + pTmp->scheduledTime = (time_t)dbHandle.getColumnToInt(index++); + + dbHandle.getColumnToString(index++, MAX_SUBJECT_LEN, pTmp->subject); + + if (pTmp->msgType.mainType == MSG_MMS_TYPE && + (pTmp->networkStatus == MSG_NETWORK_RETRIEVING || pTmp->networkStatus == MSG_NETWORK_RETRIEVE_FAIL || + pTmp->msgType.subType == MSG_NOTIFICATIONIND_MMS)){ + pTmp->pData = NULL; + index++; + }else{ + pTmp->pData = (void*)new char[pTmp->dataSize + 2]; + memset(pTmp->pData, 0x00, sizeof(pTmp->pData)); + + dbHandle.getColumnToString(index++, pTmp->dataSize+1, (char*)pTmp->pData); + + LogDebug("pTmp->pData:[" << (char*)pTmp->pData << "]"); + } + + if (addrId > 0){ + pTmp->nAddressCnt = 1; + }else{ + pTmp->nAddressCnt = 0; + } + + pTmp->addressList[0].threadId = addrId; + pTmp->addressList[0].addressType = dbHandle.getColumnToInt(index++); + pTmp->addressList[0].recipientType = dbHandle.getColumnToInt(index++); + pTmp->addressList[0].contactId = dbHandle.getColumnToInt(index++); + + dbHandle.getColumnToString(index++, MAX_ADDRESS_VAL_LEN, pTmp->addressList[0].addressVal); + + memset(displayName, 0x00, sizeof(displayName)); + dbHandle.getColumnToString(index++, MAX_DISPLAY_NAME_LEN, displayName); + + memset(firstName, 0x00, sizeof(firstName)); + dbHandle.getColumnToString(index++, MAX_DISPLAY_NAME_LEN, firstName); + + memset(lastName, 0x00, sizeof(lastName)); + dbHandle.getColumnToString(index++, MAX_DISPLAY_NAME_LEN, lastName); + + if (strlen(displayName) <= 0){ + if (strlen(firstName) > 0){ + strncpy(displayName, firstName, strlen(firstName)); + } + + if (strlen(lastName) > 0){ + strcat(displayName, " "); + strncat(displayName, lastName, strlen(lastName)); + } + }//if + + strncpy(pTmp->addressList[0].displayName, displayName, MAX_DISPLAY_NAME_LEN); + + pTmp->attachCount = dbHandle.getColumnToInt(index++); + + dbHandle.getColumnToString(index++, MSG_FILEPATH_LEN_MAX, pTmp->thumbPath); + }//for + + dbHandle.freeTable(); + + LogDebug(">>>"); + return MSG_SUCCESS; +} + +int MessageStorageReader::queryConversation(const std::string& whereClause, + /*out*/MSG_THREAD_VIEW_LIST_S *pThreadViewList){ + + pThreadViewList->nCount = 0; + pThreadViewList->msgThreadInfo = NULL; + + int rowCnt = 0; + int index = 15; // numbers of index + + std::ostringstream oStream; + std::string stringSqlQuery; + + std::string tmpWhereClause; + if(whereClause.length()==0){ + tmpWhereClause.append(" WHERE ADDRESS_ID <> 0 "); + }else{ + tmpWhereClause.append(whereClause); + } + + oStream << "SELECT ADDRESS_ID, CONTACT_ID, ADDRESS_VAL, DISPLAY_NAME, FIRST_NAME,\ + LAST_NAME, IMAGE_PATH, UNREAD_CNT, SMS_CNT, MMS_CNT, MAIN_TYPE, SUB_TYPE, \ + MSG_DIRECTION, MSG_TIME, MSG_TEXT FROM " << MSGFW_ADDRESS_TABLE_NAME << " "; + + oStream << tmpWhereClause; + stringSqlQuery = oStream.str(); + LogDebug("stringSqlQuery:[" << stringSqlQuery << "]"); + + MSG_ERROR_T err = dbHandle.getTable(stringSqlQuery.c_str(), &rowCnt); + + if (err == MSG_ERR_DB_NORECORD) { + dbHandle.freeTable(); + + return MSG_SUCCESS; + } else if (err != MSG_SUCCESS) { + LogDebug("stringSqlQuery:[" << stringSqlQuery << "]"); + + dbHandle.freeTable(); + + return err; + } + + char firstName[MAX_THREAD_NAME_LEN], lastName[MAX_THREAD_NAME_LEN]; + char displayName[MAX_DISPLAY_NAME_LEN]; + + int order = 0; + + pThreadViewList->nCount = rowCnt; + + LogDebug("pThreadViewList->nCount [" << pThreadViewList->nCount << "]"); + + pThreadViewList->msgThreadInfo = (msg_thread_view_t*) new char[sizeof(MSG_THREAD_VIEW_S*) * rowCnt]; + + MSG_THREAD_VIEW_S* pTmp = NULL; + + for (int i = 0; i < rowCnt; i++) { + pThreadViewList->msgThreadInfo[i] = (msg_thread_view_t) new char[sizeof(MSG_THREAD_VIEW_S)]; + + pTmp = (MSG_THREAD_VIEW_S*) pThreadViewList->msgThreadInfo[i]; + + pTmp->threadId = dbHandle.getColumnToInt(index++); + pTmp->contactId = dbHandle.getColumnToInt(index++); + + memset(pTmp->threadAddr, 0x00, sizeof(pTmp->threadAddr)); + dbHandle.getColumnToString(index++, MAX_THREAD_ADDR_LEN, pTmp->threadAddr); + + memset(displayName, 0x00, sizeof(displayName)); + dbHandle.getColumnToString(index++, MAX_THREAD_NAME_LEN, displayName); + + memset(firstName, 0x00, sizeof(firstName)); + dbHandle.getColumnToString(index++, MAX_THREAD_NAME_LEN, firstName); + + memset(lastName, 0x00, sizeof(lastName)); + dbHandle.getColumnToString(index++, MAX_THREAD_NAME_LEN, lastName); + + if (strlen(displayName) <= 0) { + if (order == 0) { + if (strlen(firstName) > 0) { + strncpy(displayName, firstName, strlen(firstName)); + } + + if (strlen(lastName) > 0) { + strcat(displayName, " "); + strncat(displayName, lastName, strlen(lastName)); + } + } else if (order == 1) { + if (strlen(lastName) > 0) { + strncpy(displayName, lastName, strlen(lastName)); + strcat(displayName, " "); + } + + if (strlen(firstName) > 0) { + strncat(displayName, firstName, strlen(firstName)); + } + } + } + + memset(pTmp->threadName, 0x00, sizeof(pTmp->threadName)); + strncpy(pTmp->threadName, displayName, MAX_THREAD_NAME_LEN); + + memset(pTmp->threadImagePath, 0x00, sizeof(pTmp->threadImagePath)); + dbHandle.getColumnToString(index++, MAX_IMAGE_PATH_LEN, pTmp->threadImagePath); + + pTmp->unreadCnt = dbHandle.getColumnToInt(index++); + pTmp->smsCnt = dbHandle.getColumnToInt(index++); + pTmp->mmsCnt = dbHandle.getColumnToInt(index++); + + pTmp->threadType.mainType = dbHandle.getColumnToInt(index++); + pTmp->threadType.subType = dbHandle.getColumnToInt(index++); + + pTmp->direction = dbHandle.getColumnToInt(index++); + pTmp->threadTime = (time_t) dbHandle.getColumnToInt(index++); + + memset(pTmp->threadData, 0x00, sizeof(pTmp->threadData)); + dbHandle.getColumnToString(index++, MAX_THREAD_DATA_LEN, pTmp->threadData); + } + + dbHandle.freeTable(); + + return MSG_SUCCESS; +} + diff --git a/src/platform/Tizen/Messaging/messageDB/MessageStorageReader.h b/src/platform/Tizen/Messaging/messageDB/MessageStorageReader.h new file mode 100755 index 0000000..06cd36f --- /dev/null +++ b/src/platform/Tizen/Messaging/messageDB/MessageStorageReader.h @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* + * MessageStorageReader.h + * + * Created on: 2011. 11. 16. + * Author: sangtai + */ + + + +#ifndef MessageStorageReader_H_ +#define MessageStorageReader_H_ + +#include "MsgTypes.h" +#include "MsgSqliteWrapper.h" +#include "MsgStorageTypes.h" + +#include + +class MessageStorageReader { + private: + MsgDbHandler dbHandle; + + public: + MessageStorageReader(); + virtual ~MessageStorageReader(); + + MSG_ERROR_T MsgStoConnectDB(); + MSG_ERROR_T MsgStoDisconnectDB(); + + public: + int queryMessage(const std::string& whereClause, /*out*/MSG_LIST_S *pMsgFolderViewList); + int queryConversation(const std::string& whereClause, /*out*/MSG_THREAD_VIEW_LIST_S *pThreadViewList); +}; + +#endif /* MessageStorageReader_H_ */ diff --git a/src/platform/Tizen/Messaging/messageDB/MsgSqliteWrapper.cpp b/src/platform/Tizen/Messaging/messageDB/MsgSqliteWrapper.cpp new file mode 100755 index 0000000..05911ba --- /dev/null +++ b/src/platform/Tizen/Messaging/messageDB/MsgSqliteWrapper.cpp @@ -0,0 +1,856 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include +#include +#include +#include +#include + +#include +//#include "MsgDebug.h" +#include "MsgSqliteWrapper.h" + + +#if 1 +__thread sqlite3 *handle = NULL; +__thread sqlite3_stmt *stmt = NULL; +__thread char **result = NULL; +#endif + +/*================================================================================================== + IMPLEMENTATION OF MsgDbHandler - Member Functions +==================================================================================================*/ +MsgDbHandler::MsgDbHandler() +{ + handle = NULL; + stmt = NULL; + result = NULL; +} + + +MsgDbHandler::~MsgDbHandler() +{ + if(handle != NULL) + disconnect(); + + if(stmt != NULL) + finalizeQuery(); + + if(result != NULL) + freeTable(); +} + + +MSG_ERROR_T MsgDbHandler::connect() +{ + int ret = 0; + + if (handle == NULL) + { + char strDBName[64]; + + memset(strDBName, 0x00, sizeof(strDBName)); + snprintf(strDBName, 64, "%s", MSGFW_DB_NAME); + + ret = db_util_open(strDBName, &handle, DB_UTIL_REGISTER_HOOK_METHOD); + + if (ret == SQLITE_OK) + { + LogDebug("DB Connect Success : [" << handle << "]"); + return MSG_SUCCESS; + } + else + { + LogDebug("DB Connect Fail [" << ret << "]"); + return MSG_ERR_DB_CONNECT; + } + } + else + { + LogDebug("DB Connect exist : [" << handle << "]"); + } + + return MSG_SUCCESS; +} + + +MSG_ERROR_T MsgDbHandler::disconnect() +{ + int ret = 0; + + if (handle != NULL) + { + ret = db_util_close(handle); + + if (ret == SQLITE_OK) + { + handle = NULL; + LogDebug("DB Disconnect Success"); + return MSG_SUCCESS; + } + else + { + LogDebug("DB Disconnect Fail [" << ret << "]"); + return MSG_ERR_DB_DISCONNECT; + } + } + + return MSG_SUCCESS; +} + + +bool MsgDbHandler::checkTableExist(const char *pTableName) +{ + char strQuery[256]; + int nRowCnt = 0, nResult = 0; + + /* Formulate the Query */ + memset(strQuery, 0x00, sizeof(strQuery)); + snprintf(strQuery, sizeof(strQuery), "select count(name) from sqlite_master where name='%s'", pTableName); + + if (getTable(strQuery, &nRowCnt) != MSG_SUCCESS) + { + freeTable(); + return false; + } + + nResult = getColumnToInt(1); + LogDebug("Result [" << nResult << "]"); + + freeTable(); + + if (nResult > 0) + return true; + else + return false; +} + + +MSG_ERROR_T MsgDbHandler::execQuery(const char *pQuery) +{ + int ret = 0; + + if (!pQuery) + return MSG_ERR_INVALID_PARAMETER; + + if(connect() != MSG_SUCCESS) + return MSG_ERR_DB_DISCONNECT; + + ret = sqlite3_exec(handle, pQuery, 0, 0, NULL); + + if (ret == SQLITE_OK) + { + LogDebug("Execute Query Success"); + return MSG_SUCCESS; + } + else + { + LogDebug("Execute Query Fail [" << ret << "]"); + + return MSG_ERR_DB_EXEC; + } + + return MSG_SUCCESS; +} + + +MSG_ERROR_T MsgDbHandler::getTable(const char *pQuery, int *pRowCnt) +{ + int ret = 0; + + *pRowCnt = 0; + + if(connect() != MSG_SUCCESS) + return MSG_ERR_DB_DISCONNECT; + + + ret = sqlite3_get_table(handle, pQuery, &result, pRowCnt, 0, NULL); + + if (ret == SQLITE_OK) + { + if (*pRowCnt == 0) // when the no record return 'MSG_ERR_DB_NORECORD' + { + LogDebug("No Query Result"); + return MSG_ERR_DB_NORECORD; + } + + LogDebug("Get Table Success"); + return MSG_SUCCESS; + } + else + { + LogDebug("Get Table Fail [" << ret << "]"); + return MSG_ERR_DB_GETTABLE; + } + + return MSG_SUCCESS; +} + + +void MsgDbHandler::freeTable() +{ + if (result) + { + sqlite3_free_table(result); + result = NULL; + } +} + + +MSG_ERROR_T MsgDbHandler::bindText(const char *pBindStr, int index) +{ + int ret = 0; + + if (pBindStr != NULL) + ret = sqlite3_bind_text(stmt, index, pBindStr, (strlen(pBindStr) + sizeof(unsigned char)), SQLITE_STATIC); + + return ret; +} + + +MSG_ERROR_T MsgDbHandler::bindBlob(const void * pBindBlob, int size, int index) +{ + int ret = 0; + + ret = sqlite3_bind_blob(stmt, index, pBindBlob, size, SQLITE_STATIC); + + return ret; +} + + +MSG_ERROR_T MsgDbHandler::prepareQuery(const char *pQuery) +{ + int ret = 0; + + stmt = NULL; + + if(connect() != MSG_SUCCESS) + return MSG_ERR_DB_DISCONNECT; + + + if ((ret = sqlite3_prepare_v2(handle, pQuery, strlen(pQuery), &stmt, NULL)) == SQLITE_OK) + { + LogDebug("Prepare Query Success"); + return MSG_SUCCESS; + } + else + { + LogDebug("Prepare Query Fail [" << ret << "]"); + return MSG_ERR_DB_PREPARE; + } + + return MSG_SUCCESS; +} + + +MSG_ERROR_T MsgDbHandler::stepQuery() +{ + int ret = 0; + + ret = sqlite3_step(stmt); + + if (ret == SQLITE_ROW) + { + LogDebug("MsgStepQuery() SQLITE_ROW"); + return MSG_ERR_DB_ROW; + } + else if (ret == SQLITE_DONE) + { + LogDebug("MsgStepQuery() SQLITE_DONE"); + return MSG_ERR_DB_DONE; + } + else + { + LogDebug("MsgStepQuery() Fail [" << ret << "]"); + return MSG_ERR_DB_STEP; + } + + return MSG_SUCCESS; +} + + +void MsgDbHandler::finalizeQuery() +{ + if(stmt != NULL) + sqlite3_finalize(stmt); + stmt = NULL; +} + + +int MsgDbHandler::columnInt(int ColumnIndex) +{ + return sqlite3_column_int(stmt, ColumnIndex); +} + + +const unsigned char* MsgDbHandler::columnText(int ColumnIndex) +{ + return sqlite3_column_text(stmt, ColumnIndex); +} + + +const void* MsgDbHandler::columnBlob(int ColumnIndex) +{ + return sqlite3_column_blob(stmt, ColumnIndex); +} + + +MSG_ERROR_T MsgDbHandler::beginTrans() +{ + int ret = 0; + + if(connect() != MSG_SUCCESS) + return MSG_ERR_DB_DISCONNECT; + + + ret = sqlite3_exec(handle, "BEGIN deferred;", 0, 0, NULL); + + if (ret == SQLITE_OK) + { + LogDebug("Begin Transaction Success"); + return MSG_SUCCESS; + } + else + { + LogDebug("Begin Transaction Fail [" << ret << "]"); + return MSG_ERR_DB_EXEC; + } + + return MSG_SUCCESS; +} + + +MSG_ERROR_T MsgDbHandler::endTrans(bool Success) +{ + int ret = 0; + + if(connect() != MSG_SUCCESS) + return MSG_ERR_DB_DISCONNECT; + + + if (Success == true) + { + ret = sqlite3_exec(handle, "END;", 0, 0, NULL); + } + else + { + ret = sqlite3_exec(handle, "rollback", 0, 0, NULL); + ret = sqlite3_exec(handle, "END;", 0, 0, NULL); + } + + if (ret == SQLITE_OK) + { + LogDebug("End Transaction Success"); + return MSG_SUCCESS; + } + else + { + LogDebug("End Transaction Fail [" << ret << "]"); + return MSG_ERR_DB_EXEC; + } + + return MSG_SUCCESS; +} + + +int MsgDbHandler::getColumnToInt(int RowIndex) +{ + char* pTemp = result[RowIndex]; + + int nTemp = 0; + + if (pTemp == NULL) + { + LogDebug("NULL"); + return nTemp; + } + + nTemp = (int)strtol(pTemp, (char**)NULL, 10); + +// nTemp = atoi(pTemp); + + return nTemp; +} + + +char MsgDbHandler::getColumnToChar(int RowIndex) +{ + char* pTemp = result[RowIndex]; + + if (pTemp == NULL) + { + LogDebug("NULL"); + return *pTemp; + } + + return *pTemp; +} + + +void MsgDbHandler::getColumnToString(int RowIndex, int Length, char *pString) +{ + char* pTemp = result[RowIndex]; + + if (pTemp == NULL) + { + LogDebug("NULL"); + return; + } + + strncpy(pString, pTemp, Length); +} + + +MSG_ERROR_T MsgDbHandler::getRowId(const char *pTableName, unsigned int *pRowId) +{ + int ret = 0, nRowId = 0, nRowCnt = 0; + char strQuery[256]; + + if (pTableName == NULL || pRowId == NULL) + return MSG_ERR_INVALID_PARAMETER; + + LogDebug("Table Name [" << pTableName << "]"); + + memset(strQuery, 0x00, sizeof(strQuery)); + snprintf(strQuery, sizeof(strQuery), "select max(rowid) from %s", pTableName); + + ret = getTable(strQuery, &nRowCnt); + + if (ret == SQLITE_OK) + { + nRowId = getColumnToInt(1); + + if ((nRowCnt <= 1) && (nRowId == 0)) + *pRowId = 1; + else + *pRowId = nRowId + 1; + } + else + { + LogDebug("MsgGetRowId failed"); + *pRowId = 0; + freeTable(); + return MSG_ERR_DB_GETTABLE; + } + + freeTable(); + + LogDebug("Row ID [" << *pRowId << "]"); + + return MSG_SUCCESS; +} + + +/*================================================================================================== + FUNCTION IMPLEMENTATION +==================================================================================================*/ +#if 0 +MSG_ERROR_T MsgConnectDB() +{ + int ret = 0; + + char strDBName[64]; + + memset(strDBName, 0x00, sizeof(strDBName)); + snprintf(strDBName, 64, "%s", MSGFW_DB_NAME); + + if (gDBHandle == NULL) + { + +#ifdef INCLUDE_SQLITE3 + ret = sqlite3_open(strDBName, &gDBHandle); +#else + ret = db_util_open(strDBName, &gDBHandle, DB_UTIL_REGISTER_HOOK_METHOD); +#endif + + if (ret == SQLITE_OK) + { + LogDebug("DB Connect Success"); + return MSG_SUCCESS; + } + else + { + LogDebug("DB Connect Fail [" << ret "]"); + return MSG_ERR_DB_CONNECT; + } + } + + return MSG_SUCCESS; +} + + +MSG_ERROR_T MsgDisconnectDB() +{ + int ret = 0; + + if (gDBHandle != NULL) + { + +#ifdef INCLUDE_SQLITE3 + ret = sqlite3_close(gDBHandle); +#else + ret = db_util_close(gDBHandle); +#endif + + if (ret == SQLITE_OK) + { + gDBHandle = NULL; + LogDebug("DB Disconnect Success"); + return MSG_SUCCESS; + } + else + { + LogDebug("DB Disconnect Fail [" << ret << "]"); + return MSG_ERR_DB_DISCONNECT; + } + } + + return MSG_SUCCESS; +} + + +bool MsgIsTableExist(const char *pTableName) +{ + char strQuery[256]; + int nRowCnt = 0, nResult = 0; + + /* Formulate the Query */ + memset(strQuery, 0x00, sizeof(strQuery)); + snprintf(strQuery, sizeof(strQuery), "select count(name) from sqlite_master where name='%s'", pTableName); + + if (MsgGetTable(strQuery, &nRowCnt) != MSG_SUCCESS) + { + MsgFreeTable(); + return false; + } + + nResult = MsgGetColumnToInt(1); + LogDebug("Result [" << nResult << "]"); + + MsgFreeTable(); + + if (nResult > 0) + return true; + else + return false; +} + + +MSG_ERROR_T MsgExecQuery(const char *pQuery) +{ + int ret = 0; + + if (!pQuery) + return MSG_ERR_INVALID_PARAMETER; + + ret = sqlite3_exec(gDBHandle, pQuery, 0, 0, NULL); + + if (ret == SQLITE_OK) + { + LogDebug("Execute Query Success"); + return MSG_SUCCESS; + } + else + { + LogDebug("Execute Query Fail [" << ret << "]"); + return MSG_ERR_DB_EXEC; + } + + return MSG_SUCCESS; +} + + +MSG_ERROR_T MsgGetTable(const char *pQuery, int *pRowCnt) +{ + int ret = 0; + + *pRowCnt = 0; + + ret = sqlite3_get_table(gDBHandle, pQuery, &gQueryResult, pRowCnt, 0, NULL); + + if (ret == SQLITE_OK) + { + if (*pRowCnt == 0) // when the no record return 'MSG_ERR_DB_NORECORD' + { + LogDebug("No Query Result"); + return MSG_ERR_DB_NORECORD; + } + + LogDebug("Get Table Success"); + return MSG_SUCCESS; + } + else + { + LogDebug("Get Table Fail [" << ret << "]"); + return MSG_ERR_DB_GETTABLE; + } + + return MSG_SUCCESS; +} + + +void MsgFreeTable() +{ + if (gQueryResult) + { + sqlite3_free_table(gQueryResult); + gQueryResult = NULL; + } +} + +/* End of supporting two queries simultaneously*/ + +MSG_ERROR_T MsgBindText(const char *pBindStr, int index) +{ + int ret = 0; + + if (pBindStr != NULL) + ret = sqlite3_bind_text(gStmt, index, pBindStr, (strlen(pBindStr) + sizeof(unsigned char)), SQLITE_STATIC); + + return ret; +} + + +MSG_ERROR_T MsgBindBlob(const void * pBindBlob, int size, int index) +{ + int ret = 0; + + ret = sqlite3_bind_blob(gStmt, index, pBindBlob, size, SQLITE_STATIC); + + return ret; +} + + +MSG_ERROR_T MsgPrepareQuery(const char *pQuery) +{ + int ret = 0; + + gStmt = NULL; + + if ((ret = sqlite3_prepare_v2(gDBHandle, pQuery, strlen(pQuery), &gStmt, NULL)) == SQLITE_OK) + { + LogDebug("Prepare Query Success"); + return MSG_SUCCESS; + } + else + { + LogDebug("Prepare Query Fail [" << ret "]"); + return MSG_ERR_DB_PREPARE; + } + + return MSG_SUCCESS; +} + + +MSG_ERROR_T MsgStepQuery() +{ + int ret = 0; + + ret = sqlite3_step(gStmt); + + if (ret == SQLITE_ROW) + { + LogDebug("MsgStepQuery() SQLITE_ROW"); + return MSG_ERR_DB_ROW; + } + else if (ret == SQLITE_DONE) + { + LogDebug("MsgStepQuery() SQLITE_DONE"); + return MSG_ERR_DB_DONE; + } + else + { + LogDebug("MsgStepQuery() Fail [" << ret << "]"); + return MSG_ERR_DB_STEP; + } + + return MSG_SUCCESS; +} + + +void MsgFinalizeQuery() +{ + sqlite3_finalize(gStmt); + gStmt = NULL; +} + + +int MsgColumnInt(int ColumnIndex) +{ + return sqlite3_column_int(gStmt, ColumnIndex); +} + + +const unsigned char* MsgColumnText(int ColumnIndex) +{ + return sqlite3_column_text(gStmt, ColumnIndex); +} + + +const void* MsgColumnBlob(int ColumnIndex) +{ + return sqlite3_column_blob(gStmt, ColumnIndex); +} + + +MSG_ERROR_T MsgBeginTrans() +{ + int ret = 0; + + ret = sqlite3_exec(gDBHandle, "BEGIN deferred;", 0, 0, NULL); + + if (ret == SQLITE_OK) + { + LogDebug("Begin Transaction Success"); + return MSG_SUCCESS; + } + else + { + LogDebug("Begin Transaction Fail [" << ret "]"); + return MSG_ERR_DB_EXEC; + } + + return MSG_SUCCESS; +} + + +MSG_ERROR_T MsgEndTrans(bool Success) +{ + int ret = 0; + + if (Success == true) + { + ret = sqlite3_exec(gDBHandle, "END;", 0, 0, NULL); + } + else + { + ret = sqlite3_exec(gDBHandle, "rollback", 0, 0, NULL); + ret = sqlite3_exec(gDBHandle, "END;", 0, 0, NULL); + } + + if (ret == SQLITE_OK) + { + LogDebug("End Transaction Success"); + return MSG_SUCCESS; + } + else + { + LogDebug("End Transaction Fail [" << ret << "]"); + return MSG_ERR_DB_EXEC; + } + + return MSG_SUCCESS; +} + + +int MsgGetColumnToInt(int RowIndex) +{ + char* pTemp = gQueryResult[RowIndex]; + + int nTemp = 0; + + if (pTemp == NULL) + { + LogDebug("NULL"); + return nTemp; + } + + nTemp = (int)strtol(pTemp, (char**)NULL, 10); + +// nTemp = atoi(pTemp); + + return nTemp; +} + + +char MsgGetColumnToChar(int RowIndex) +{ + char* pTemp = gQueryResult[RowIndex]; + + if (pTemp == NULL) + { + LogDebug("NULL"); + return NULL; + } + + return *pTemp; +} + + +void MsgGetColumnToString(int RowIndex, int Length, char *pString) +{ + char* pTemp = gQueryResult[RowIndex]; + + if (pTemp == NULL) + { + LogDebug("NULL"); + return; + } + + strncpy(pString, pTemp, Length); +} + + +MSG_ERROR_T MsgGetRowId(const char *pTableName, unsigned int *pRowId) +{ + int ret = 0, nRowId = 0, nRowCnt = 0; + char strQuery[256]; + + if (pTableName == NULL || pRowId == NULL) + return MSG_ERR_INVALID_PARAMETER; + + LogDebug("Table Name [" << pTableName << "]"); + + memset(strQuery, 0x00, sizeof(strQuery)); + snprintf(strQuery, sizeof(strQuery), "select max(rowid) from %s", pTableName); + + ret = MsgGetTable(strQuery, &nRowCnt); + + if (ret == SQLITE_OK) + { + nRowId = MsgGetColumnToInt(1); + + if ((nRowCnt <= 1) && (nRowId == 0)) + *pRowId = 1; + else + *pRowId = nRowId + 1; + } + else + { + LogDebug("MsgGetRowId failed"); + *pRowId = 0; + MsgFreeTable(); + return MSG_ERR_DB_GETTABLE; + } + + MsgFreeTable(); + + LogDebug("Row ID [" << *pRowId << "]"); + + return MSG_SUCCESS; +} +#endif + +void MsgReleaseMemoryDB() +{ + int freeSize = 0; + + freeSize = sqlite3_release_memory(-1); + + LogDebug("freed memory size (bytes) : [" << freeSize << "]"); +} + diff --git a/src/platform/Tizen/Messaging/messageDB/MsgSqliteWrapper.h b/src/platform/Tizen/Messaging/messageDB/MsgSqliteWrapper.h new file mode 100755 index 0000000..4d9b3e3 --- /dev/null +++ b/src/platform/Tizen/Messaging/messageDB/MsgSqliteWrapper.h @@ -0,0 +1,135 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef MSG_SQLITE_WRAPPER_H +#define MSG_SQLITE_WRAPPER_H + +/*================================================================================================== + INCLUDE FILES +==================================================================================================*/ +#include "MsgTypes.h" + +extern "C" +{ + #include +} + + +/*================================================================================================== + DEFINES +==================================================================================================*/ +#define MSGFW_DB_NAME "/opt/dbspace/.msg_service.db" + +#define MSGFW_MESSAGE_TABLE_NAME "MSG_MESSAGE_TABLE" +#define MSGFW_FOLDER_TABLE_NAME "MSG_FOLDER_TABLE" +#define MSGFW_ADDRESS_TABLE_NAME "MSG_ADDRESS_TABLE" +#define MSGFW_SIM_MSG_TABLE_NAME "MSG_SIM_TABLE" +#define MSGFW_FILTER_TABLE_NAME "MSG_FILTER_TABLE" +#define MSGFW_PUSH_MSG_TABLE_NAME "MSG_PUSH_TABLE" +#define MSGFW_CB_MSG_TABLE_NAME "MSG_CBMSG_TABLE" +#define MMS_PLUGIN_MESSAGE_TABLE_NAME "MSG_MMS_MESSAGE_TABLE" +#define MMS_PLUGIN_ATTRIBUTE_TABLE_NAME "MSG_MMS_ATTR_TABLE" +#define MSGFW_SYNCML_MSG_TABLE_NAME "MSG_SYNCML_TABLE" +#define MSGFW_SCHEDULED_MSG_TABLE_NAME "MSG_SCHEDULED_TABLE" +#define MSGFW_SMS_SENDOPT_TABLE_NAME "MSG_SMS_SENDOPT_TABLE" +#define MSGFW_REPORT_TABLE_NAME "MSG_REPORT_TABLE" + +#define MAX_QUERY_LEN 3072 +#define MAX_FOLDER_NAME_LEN 20 +#define MAX_ACCOUNT_NAME_LEN 51 + +#define MAX_THREAD_ADDR_LEN 40 +#define MAX_THREAD_NAME_LEN 195 +#define MAX_THREAD_DATA_LEN 128 + + +/*================================================================================================== + FUNCTION PROTOTYPES +==================================================================================================*/ +#if 0 +MSG_ERROR_T MsgConnectDB(); +MSG_ERROR_T MsgDisconnectDB(); +bool MsgIsTableExist(const char *pTableName); + +MSG_ERROR_T MsgExecQuery(const char *pQuery); + +MSG_ERROR_T MsgGetTable(const char *pQuery, int *pRowCnt); +void MsgFreeTable(); + +MSG_ERROR_T MsgBindText(const char *pBindStr, int index); +MSG_ERROR_T MsgBindBlob(const void * pBindBlob, int size, int index); + +MSG_ERROR_T MsgPrepareQuery(const char *pQuery); +MSG_ERROR_T MsgStepQuery(); +void MsgFinalizeQuery(); + +int MsgColumnInt(int ColumnIndex); +const unsigned char* MsgColumnText(int ColumnIndex); +const void* MsgColumnBlob(int ColumnIndex); + +MSG_ERROR_T MsgBeginTrans(); +MSG_ERROR_T MsgEndTrans(bool Success); + +int MsgGetColumnToInt(int RowIndex); +void MsgGetColumnToString(int RowIndex, int Length, char *pString); + +MSG_ERROR_T MsgGetRowId(const char *pTableName, unsigned int *pRowId); +#endif + +void MsgReleaseMemoryDB(); + + +/*================================================================================================== + CLASS DEFINITIONS +==================================================================================================*/ +class MsgDbHandler +{ +public: + MsgDbHandler(); + ~MsgDbHandler(); + + MSG_ERROR_T connect(); + MSG_ERROR_T disconnect(); + + bool checkTableExist(const char *pTableName); + MSG_ERROR_T execQuery(const char *pQuery); + MSG_ERROR_T getTable(const char *pQuery, int *pRowCnt); + void freeTable(); + MSG_ERROR_T bindText(const char *pBindStr, int index); + MSG_ERROR_T bindBlob(const void * pBindBlob, int size, int index); + MSG_ERROR_T prepareQuery(const char *pQuery); + MSG_ERROR_T stepQuery(); + void finalizeQuery(); + int columnInt(int ColumnIndex); + const unsigned char* columnText(int ColumnIndex); + const void* columnBlob(int ColumnIndex); + MSG_ERROR_T beginTrans(); + MSG_ERROR_T endTrans(bool Success); + int getColumnToInt(int RowIndex); + char getColumnToChar(int RowIndex); + void getColumnToString(int RowIndex, int Length, char *pString); + MSG_ERROR_T getRowId(const char *pTableName, unsigned int *pRowId); + +private: + +// sqlite3 *handle; +// sqlite3_stmt *stmt; +// char **result; + +}; + +#endif // MSG_SQLITE_WRAPPER_H + diff --git a/src/platform/Tizen/NFC/NFCManager.cpp b/src/platform/Tizen/NFC/NFCManager.cpp new file mode 100755 index 0000000..407b9d4 --- /dev/null +++ b/src/platform/Tizen/NFC/NFCManager.cpp @@ -0,0 +1,421 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include "NFCManager.h" +#include "NFCUtil.h" + +using namespace TizenApis::Api::NFC; +using namespace DPL; + +namespace TizenApis { +namespace Platform { +namespace NFC { + +namespace +{ + static void TagDetectedCallback(nfc_discovered_type_e type, nfc_tag_h tag, void *data) { + LogDebug("Callback TagDetectedCallback."); + + if (data) { + if (NFC_DISCOVERED_TYPE_ATTACHED == type) { + (static_cast(data))->updateCurrentHandle((void *)tag); + (static_cast(data))->NFCHasDetected((void *)tag, NFC_TAG_TYPE); + } else { + (static_cast(data))->updateCurrentHandle(NULL); + (static_cast(data))->NFCHasDetected(NULL, NFC_TAG_TYPE); + } + } else { + LogError("Callback private data is NULL."); + } + + } + + static void TargetDetectedCallback(nfc_discovered_type_e type, nfc_p2p_target_h target, void *data) { + LogDebug("Callback TargetDetectedCallback."); + + if (data) { + if (NFC_DISCOVERED_TYPE_ATTACHED == type) { + (static_cast(data))->updateCurrentHandle((void *)target); + (static_cast(data))->NFCHasDetected((void *)target, NFC_TARGET_TYPE); + } else { + (static_cast(data))->updateCurrentHandle(NULL); + (static_cast(data))->NFCHasDetected(NULL, NFC_TARGET_TYPE); + } + } else { + LogError("Callback private data is NULL."); + } + + } + + static void NDEFDetectedCallback(nfc_ndef_message_h message, void *data) { + LogDebug("Callback NDEFDetectedCallback."); + if (data) { + unsigned char *UrawData; + int size; + + if (nfc_ndef_message_get_rawdata(message, &UrawData, &size) != NFC_ERROR_NONE) { + LogError("Can't get rawdata of message"); + return; + } + + NFCUtil Util; + (static_cast(data))->NDEFHasDetected(Util.toVector(UrawData, size)); + + } else { + LogError("Callback private data is NULL."); + } + } + + static void SeEventCallback(nfc_se_event_e event, void *data) { + LogDebug("Callback NDEFDetectedCallback."); + if (data) { + nfcSeEventType seEvent = NFC_SE_EVENTTYPE_END_TRANSACTION; + switch(event) { + case NFC_SE_EVENT_START_TRANSACTION: + seEvent = NFC_SE_EVENTTYPE_START_TRANSACTION; + break; + case NFC_SE_EVENT_END_TRANSACTION: + seEvent = NFC_SE_EVENTTYPE_END_TRANSACTION; + break; + case NFC_SE_EVENT_CONNECTIVITY: + seEvent = NFC_SE_EVENTTYPE_CONNECTIVITY; + break; + case NFC_SE_EVENT_FIELD_ON: + seEvent = NFC_SE_EVENTTYPE_FIELD_ON; + break; + case NFC_SE_EVENT_FIELD_OFF: + seEvent = NFC_SE_EVENTTYPE_FIELD_OFF; + break; + } + (static_cast(data))->SeEventHasDetected(seEvent); + + } else { + LogError("Callback private data is NULL."); + } + } +}//private namespace + +NFCManager::NFCManager() + :m_initialized(false) { + LogDebug("Platform::NFC Enter"); + initialize(); + curHandle = NULL; + + m_managerPriv = NULL; + + m_NFCTagEmitterPtr.Reset(); + m_NFCTargetEmitterPtr.Reset(); + m_NdefEmitterPtr.Reset(); + m_SeEventEmitterPtr.Reset(); + + m_tagFilter.Reset(); + +} + +NFCManager::~NFCManager() { + LogDebug("Enter"); + int result = -1; + if(m_initialized == true) +{ + result = nfc_manager_deinitialize (); + if (result !=NFC_ERROR_NONE) { + LogInfo("failed to deinitialize nfc"); + } + } + + nfc_manager_unset_tag_discovered_cb(); + nfc_manager_unset_p2p_target_discovered_cb(); + nfc_manager_unset_ndef_discovered_cb(); + nfc_manager_unset_se_event_cb(); + + m_managerPriv = NULL; + + LogDebug("destroy nfc"); +} + +int NFCManager::setTagListener(const EventNFCChangedEmitterPtr& emitter, + TagFilterPtr pFilter, void *managerPriv) { + LogDebug(" NFCManager::setTagListener Entered"); + int result = -1; + + if (m_NFCTagEmitterPtr.Get() != NULL) + Throw(WrtDeviceApis::Commons::AlreadyInUseException); + + m_NFCTagEmitterPtr = emitter; + m_managerPriv = managerPriv; + + LogDebug(" NFCManager::setTagListener set discovered callback, filter size == " << pFilter->getFilterSize()); + + m_tagFilter = pFilter; + if (pFilter->getFilterSize() > 0) { + int filter = NFC_TAG_FILTER_ALL_DISABLE; + for (int cnt = 0; cnt < pFilter->getFilterSize() ; cnt++) { + LogDebug(" NFCManager::setTagListener filter == " << pFilter->getFilterValue(cnt)); + if ((pFilter->getFilterValue(cnt) >= NFC_TAGTYPE_ISO14443_A_PICC) && (pFilter->getFilterValue(cnt) <= NFC_TAGTYPE_MIFARE_DESFIRE_PICC)) + filter = filter |NFC_TAG_FILTER_ISO14443A_ENABLE; + else if ((pFilter->getFilterValue(cnt) >= NFC_TAGTYPE_ISO14443_B_PICC) && (pFilter->getFilterValue(cnt) <= NFC_TAGTYPE_ISO14443_BPRIME_PICC)) + filter = filter |NFC_TAG_FILTER_ISO14443B_ENABLE; + else if (pFilter->getFilterValue(cnt) == NFC_TAGTYPE_FELICA_PICC) + filter = filter |NFC_TAG_FILTER_FELICA_ENABLE ; + else if (pFilter->getFilterValue(cnt) == NFC_TAGTYPE_JEWEL_PICC) + filter = filter |NFC_TAG_FILTER_JEWEL_ENABLE ; + else if (pFilter->getFilterValue(cnt) == NFC_TAGTYPE_ISO15693_PICC) + filter = filter |NFC_TAG_FILTER_ISO15693_ENABLE ; + } + nfc_manager_set_tag_filter(filter); + } else { + nfc_manager_set_tag_filter(NFC_TAG_FILTER_ALL_ENABLE); + } + + result = nfc_manager_set_tag_discovered_cb (TagDetectedCallback, this); + if (result != NFC_ERROR_NONE) + { + LogInfo("failed to set callback of nfc_manager_set_ndef_discovered_cb"); + return result; + } + LogInfo("NFCManager::setNDEFListener : result << " << result); + return result; +} + +int NFCManager::setPeerListener(const EventNFCChangedEmitterPtr& emitter, void *managerPriv) { + LogDebug(" NFCManager::setPeerListener Entered"); + int result = -1; + + if (m_NFCTargetEmitterPtr.Get() != NULL) + Throw(WrtDeviceApis::Commons::AlreadyInUseException); + + m_NFCTargetEmitterPtr = emitter; + m_managerPriv = managerPriv; + result = nfc_manager_set_p2p_target_discovered_cb (TargetDetectedCallback, this); + + if (result != NFC_ERROR_NONE) + { + LogInfo("failed to set callback of nfc_manager_set_p2p_target_discovered_cb"); + return result; + } + + LogInfo("NFCManager::setPeerListener : result << " << result); + return result; +} + +int NFCManager::setNDEFListener(const EventNFCChangedNdefEmitterPtr& emitter) { + LogDebug(" NFCManager::setNDEFListener Entered"); + int result = -1; + + if (m_NdefEmitterPtr.Get() != NULL) + Throw(WrtDeviceApis::Commons::AlreadyInUseException); + + m_NdefEmitterPtr = emitter; + result = nfc_manager_set_ndef_discovered_cb(NDEFDetectedCallback, this); + if (result != NFC_ERROR_NONE) + { + LogInfo("failed to set callback of nfc_manager_set_ndef_discovered_cb"); + return result; + } + LogInfo("NFCManager::setNDEFListener : result << " << result); + return result; +} + +int NFCManager::setSEEventListener(const EventNFCChangedSeEventEmitterPtr& emitter) { + LogDebug(" NFCManager::setNDEFListener Entered"); + int result = -1; + + if (m_SeEventEmitterPtr.Get() != NULL) + Throw(WrtDeviceApis::Commons::AlreadyInUseException); + + m_SeEventEmitterPtr = emitter; + result = nfc_manager_set_se_event_cb (SeEventCallback, this); + if (result != NFC_ERROR_NONE) + { + LogInfo("failed to set callback of NFC_manager_set_tag_discovered_cb"); + return result; + } + LogInfo("NFCManager::setSEEventListener : result << " << result); + return result; +} + +void NFCManager::unsetTagListener(/*EventNFCChangedEmitter::IdType id*/) { + LogDebug(" NFCManager::unsetTagListener Entered"); + + nfc_manager_unset_tag_discovered_cb (); + m_NFCTagEmitterPtr.Reset(); + } + +void NFCManager::unsetPeerListener(/*EventNFCChangedEmitter::IdType id*/) { + LogDebug(" NFCManager::unsetPeerListener Entered"); + nfc_manager_unset_p2p_target_discovered_cb(); + m_NFCTargetEmitterPtr.Reset(); +} + + +void NFCManager::unsetNDEFListener() { + LogDebug(" NFCManager::unsetNDEFListener Entered"); + nfc_manager_unset_ndef_discovered_cb(); + m_NdefEmitterPtr.Reset(); +} + +void NFCManager::unsetSEEventListener() { + LogDebug(" NFCManager::unsetSEEventListener Entered"); + nfc_manager_unset_se_event_cb(); + m_SeEventEmitterPtr.Reset(); +} + +void NFCManager::NFCHasDetected(void *props, EventNFCType type) +{ + LogDebug("NFCManager::NFCHasDetected Enter type : " << type); + + if (((m_NFCTagEmitterPtr.Get() != NULL) && (type == NFC_TAG_TYPE)) || + ((m_NFCTargetEmitterPtr.Get() != NULL) && (type == NFC_TARGET_TYPE))){ + EventNFCType nfcType = type; + + if ((props != NULL) && (type == NFC_TAG_TYPE)) { + + nfc_tag_type_e tagType; + + if (nfc_tag_get_type((nfc_tag_h)props, &tagType) == NFC_ERROR_NONE) { + LogDebug("NFCManager::NFCHasDetected Tag real type : " << tagType); + int cnt; + for (cnt = 0; cnt < m_tagFilter->getFilterSize() ; cnt++) { + NFCUtil Util; + if (Util.convertTonfcTagType(static_cast(tagType)) == m_tagFilter->getFilterValue(cnt)) + break; + } + if ((m_tagFilter->getFilterSize() > 0) && (cnt == m_tagFilter->getFilterSize())) { + LogDebug("Filter doesn't have this tag type "); + return; + } + + switch(tagType) { + case NFC_MIFARE_MINI_PICC: + case NFC_MIFARE_1K_PICC: + case NFC_MIFARE_4K_PICC: + nfcType = NFC_TAG_MIFARE_CLASSIC_TYPE; + break; + case NFC_MIFARE_ULTRA_PICC: + nfcType = NFC_TAG_MIFARE_ULTRA_TYPE; + break; + default: + nfcType = NFC_TAG_TYPE; + break; + } + } else { + LogDebug("It can't get real nfc tag type"); + int cnt; + for (cnt = 0; cnt < m_tagFilter->getFilterSize() ; cnt++) { + if (NFC_TAGTYPE_GENERIC_PICC == m_tagFilter->getFilterValue(cnt)) + break; + } + + if (cnt == m_tagFilter->getFilterSize()) { + LogDebug("Filter doesn't have this tag type "); + return; + } + + } + } + + EventNFCChangedPtr event( new EventNFCChanged() ); + LogDebug("nfc type was detected"); + if (props == NULL) + event->setNFCStatus(NFC_DETATCHED); + else + event->setNFCStatus(NFC_ATTATCHED); + event->setNFCProperties(props); + event->setNFCType(nfcType); + event->setPrivateNFCManagerPtr(m_managerPriv); + LogDebug("emit event with nfc tag info"); + if (type == NFC_TARGET_TYPE) + m_NFCTargetEmitterPtr->emit(event); + else + m_NFCTagEmitterPtr->emit(event); + } else { + LogDebug("m_NFCTagEmitterPtr.Get() != NULL ? " << (m_NFCTagEmitterPtr.Get() != NULL)); + } + + +} + +void NFCManager::NDEFHasDetected(std::vector data) +{ + LogDebug("NFCManager::NFCHasDetected Enter"); + + if (m_NdefEmitterPtr.Get() != NULL) { + EventNFCChangedNdefPtr event( new EventNFCChangedNdef() ); + LogDebug("nfc type was detected"); + + event->setReadNdefResult(data); + LogDebug("emit event with nfc tag info"); + m_NdefEmitterPtr->emit(event); + } +} + +void NFCManager::SeEventHasDetected(nfcSeEventType eventType) +{ + LogDebug("NDEF is detected Enter"); + + if (m_SeEventEmitterPtr.Get() != NULL) { + EventNFCChangedSeEventPtr event( new EventNFCChangedSeEvent() ); + event->setSeEvent(eventType); + m_SeEventEmitterPtr->emit(event); + } +} + +void NFCManager::initialize() { + LogDebug("NFCManager::initialize Entered"); + int result = -1; + result = nfc_manager_initialize(); + if (result != NFC_ERROR_NONE) { + LogError("Could not initialize NFC."); + Throw(WrtDeviceApis::Commons::UnsupportedException); + m_initialized = false; + } + m_initialized = true; + return; +} + +void *NFCManager::getCachedMessage() { + LogDebug("Entered"); + nfc_ndef_message_h messageHandle; + int result = nfc_manager_get_cached_message(&messageHandle); + if (result == NFC_ERROR_INVALID_NDEF_MESSAGE) + return NULL; + if (result != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get cached message"); + + return (void *)(messageHandle); +} + +bool NFCManager::isValidHandle(void * handle) { + LogDebug("Entered"); + if ((handle != NULL) && (handle == curHandle)) + return TRUE; + + return FALSE; +} + +void NFCManager::updateCurrentHandle(void *handle) { + LogDebug("Updated!"); + curHandle = handle; +} + +} +} +} diff --git a/src/platform/Tizen/NFC/NFCManager.h b/src/platform/Tizen/NFC/NFCManager.h new file mode 100755 index 0000000..4055762 --- /dev/null +++ b/src/platform/Tizen/NFC/NFCManager.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _MFCMANAGER_H_ +#define _MFCMANAGER_H_ + +#include +#include + +#include +#include +#include +#include + +using namespace TizenApis::Api::NFC; + +namespace TizenApis { +namespace Platform { +namespace NFC { +class NFCManager : public INFCManager +{ + friend class NFCFactory; + public: + NFCManager(); + virtual ~NFCManager(); + +public: + /** + * watchNFCTag + */ + virtual int setTagListener(const EventNFCChangedEmitterPtr& emitter, TagFilterPtr filter, void *managerPriv); + virtual int setPeerListener(const EventNFCChangedEmitterPtr& emitter, void *managerPriv); + virtual int setNDEFListener(const EventNFCChangedNdefEmitterPtr& emitter); + virtual int setSEEventListener(const EventNFCChangedSeEventEmitterPtr& emitter); + + /** + * clearWatch + */ + virtual void unsetTagListener(); + virtual void unsetPeerListener(); + virtual void unsetNDEFListener(); + virtual void unsetSEEventListener(); + + virtual void NFCHasDetected(void *props, EventNFCType type); + virtual void NDEFHasDetected(std::vector data); + virtual void SeEventHasDetected(nfcSeEventType event); + + virtual void *getCachedMessage(); + virtual bool isValidHandle(void * handle); + virtual void updateCurrentHandle(void *handle); + +private: + /** + * Initialize NFC. + */ + void initialize(); + + EventNFCChangedEmitterPtr m_NFCTagEmitterPtr; + EventNFCChangedEmitterPtr m_NFCTargetEmitterPtr; + EventNFCChangedNdefEmitterPtr m_NdefEmitterPtr; + EventNFCChangedSeEventEmitterPtr m_SeEventEmitterPtr; + TagFilterPtr m_tagFilter; + void *m_managerPriv; + + bool m_initialized; +}; +} +} +} + +#endif /* _MFCMANAGER_H_ */ diff --git a/src/platform/Tizen/NFC/NFCTag.cpp b/src/platform/Tizen/NFC/NFCTag.cpp new file mode 100755 index 0000000..2f18479 --- /dev/null +++ b/src/platform/Tizen/NFC/NFCTag.cpp @@ -0,0 +1,319 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#include + +#include + +#include "NFCTag.h" +#include "NFCUtil.h" + +namespace TizenApis { +namespace Platform { +namespace NFC { + +using namespace Api::NFC; +using namespace WrtDeviceApis; + +namespace +{ + /** + * Callback method called by platform as interval time. + * @param event_type Platform magnetic evet type + * @param event Platform sensor event data + * @param this_ User data pointer. + */ + static bool TagInformationCallback(const char *key, const unsigned char *value, int value_size, void *user_data) { + LogDebug("Callback TagInformationCallback."); + if (user_data) { + NFCUtil Util; + (static_cast(user_data))->makeTagProperties(key, Util.toVector(value, value_size)); + return TRUE; + } + LogDebug("Error! TagInformationCallback is Null."); + return false; + } + + static void TagReadCallback(nfc_error_e result , nfc_ndef_message_h message , void * data) { + LogDebug("Callback TagReadCallback."); + if (data) { + + LogDebug("message handler :" << message); + + unsigned char *UrawData; + int size; + if (nfc_ndef_message_get_rawdata(message, &UrawData, &size) != NFC_ERROR_NONE) { + LogError("Can't get record's rawdata"); + return; + } + + NFCUtil Util; + ((NFCTag *)data)->readNdefManualAnswer((int)result, Util.toVector(UrawData, size)); + + + } else { + LogDebug("Error! TagReadCallback is Null."); + } + } + + static void TagWriteCallback(nfc_error_e result , void * data) { + LogDebug("Callback TagWriteCallback."); + if (data) { + ((NFCTag *)data)->writeNdefManualAnswer((int)result); + } else { + LogDebug("Error! TagWriteCallback is Null."); + } + } + + static void TagTransceiveCallback(nfc_error_e result , unsigned char * buffer, int buffer_size, void * data) { + LogDebug("Callback TagTransceiveCallback."); + if (data) { + NFCUtil Util; + + ((NFCTag *)data)->transceiveManualAnswer((int)result, Util.toVector(buffer, buffer_size)); + } else { + LogDebug("Error! TagTransceiveCallback is Null."); + } + } + + static void TagFormatCallback(nfc_error_e result, void * data) { + LogDebug("Callback TagFormatCallback."); + if (data) { + ((NFCTag *)data)->formatManualAnswer((int)result); + } else { + LogDebug("Error! TagFormatCallback is Null."); + } + } +}//private namespace + +NFCTag::NFCTag(void *tagHandle) +{ + LogDebug("entered"); + + handle = (nfc_tag_h)tagHandle; +} + +NFCTag::~NFCTag() +{ + LogDebug("entered"); + handle = NULL; +} + +void *NFCTag::getHandle() { + return (void *)handle; +} + +nfcTagType NFCTag::getTagType() { + nfc_tag_type_e type = NFC_UNKNOWN_TARGET; + if (nfc_tag_get_type(handle, &type) != NFC_ERROR_NONE) + ThrowMsg(Commons::PlatformException, "Can't get tag Type"); + + NFCUtil Util; + return Util.convertTonfcTagType(type); +} + +bool NFCTag::isNDEFSupport() { + bool isNDEF = FALSE; + if (nfc_tag_is_support_ndef(handle, &isNDEF) != NFC_ERROR_NONE) + ThrowMsg(Commons::PlatformException, "Can't get if Ndef is supported"); + return isNDEF; +} +long NFCTag::getNdefSize(){ + unsigned int ndefSize; + if (nfc_tag_get_ndef_size(handle, &ndefSize) != NFC_ERROR_NONE) + ThrowMsg(Commons::PlatformException, "Can't get Ndef size"); + + return static_cast(ndefSize); +} +std::vector NFCTag::getProperties() { + LogDebug("Enter"); + props.clear(); + if(nfc_tag_foreach_information(handle, TagInformationCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::PlatformException, "call back set error"); + } + + return props; +} + +void NFCTag::makeTagProperties(const char *key, std::vector value) { + NFCTagProperties newProp; + newProp.key = key; + newProp.value = value; + props.push_back(newProp); +} + +void NFCTag::readNdef(const EventTagActionReadPtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTag::writeNdef(const EventTagActionWritePtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTag::transceive(const EventTagActionTransceivePtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTag::format(const EventTagActionFormatPtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTag::readNdefManualAnswer(int result , std::vector data) +{ + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagActionReadPtr->setResult(TRUE); + m_EventTagActionReadPtr->setReadNdefResult(data); + + } else { + m_EventTagActionReadPtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagActionReadPtr); +} + +void NFCTag::writeNdefManualAnswer(int result) +{ + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagActionWritePtr->setResult(TRUE); + } else { + m_EventTagActionWritePtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagActionWritePtr); +} + +void NFCTag::transceiveManualAnswer(int result , std::vector data) +{ + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagActionTransceivePtr->setResult(TRUE); + m_EventTagActionTransceivePtr->setTransceiveBuffer(data); + } else { + m_EventTagActionTransceivePtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagActionTransceivePtr); +} + +void NFCTag::formatManualAnswer(int result ) +{ + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagActionFormatPtr->setResult(TRUE); + } else { + m_EventTagActionFormatPtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagActionFormatPtr); +} + +void NFCTag::OnRequestReceived(const EventTagActionReadPtr& event) { + LogDebug("Enter"); + + try { + event->switchToManualAnswer(); + + m_EventTagActionReadPtr = event; + + if( nfc_tag_read_ndef(handle, TagReadCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + +void NFCTag::OnRequestReceived(const EventTagActionWritePtr& event) { + + try { + event->switchToManualAnswer(); + + m_EventTagActionWritePtr = event; + if( nfc_tag_write_ndef(handle, (nfc_ndef_message_h)event->getNdefForWriting(),TagWriteCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + +void NFCTag::OnRequestReceived(const EventTagActionTransceivePtr& event) { + + try { + event->switchToManualAnswer(); + + m_EventTagActionTransceivePtr = event; + + NFCUtil Util; + if( nfc_tag_transceive(handle, Util.toCharPtr(event->getTransceiveBuffer()), event->getTransceiveBufferSize(), TagTransceiveCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + +void NFCTag::OnRequestReceived(const EventTagActionFormatPtr& event) { + + try { + event->switchToManualAnswer(); + + m_EventTagActionFormatPtr = event; + + NFCUtil Util; + LogDebug("key size :" << event->getKeySize()); + if( nfc_tag_format_ndef(handle, Util.toCharPtr(event->getKey()), event->getKeySize(), TagFormatCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + + +} +} +} diff --git a/src/platform/Tizen/NFC/NFCTag.h b/src/platform/Tizen/NFC/NFCTag.h new file mode 100755 index 0000000..a7f87d8 --- /dev/null +++ b/src/platform/Tizen/NFC/NFCTag.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _NFCTAG_H_ +#define _NFCTAG_H_ + +#include +#include + +using namespace TizenApis::Api::NFC; + +namespace TizenApis { +namespace Platform { +namespace NFC { + +class NFCTag : public INFCTag +{ + friend class NFCFactory; + public: + NFCTag(void *tagHandle); + virtual ~NFCTag(); + + virtual void *getHandle(); + virtual nfcTagType getTagType(); + virtual bool isNDEFSupport(); + virtual long getNdefSize(); + virtual std::vector getProperties(); + virtual void readNdef(const EventTagActionReadPtr& event); + virtual void writeNdef(const EventTagActionWritePtr& event); + virtual void transceive(const EventTagActionTransceivePtr& event); + virtual void format(const EventTagActionFormatPtr& event); + + virtual void readNdefManualAnswer(int result , std::vector data); + virtual void writeNdefManualAnswer(int result ); + virtual void transceiveManualAnswer(int result , std::vector data); + virtual void formatManualAnswer(int result); + + void makeTagProperties(const char *key, std::vector value); + private: + EventTagActionReadPtr m_EventTagActionReadPtr; + EventTagActionWritePtr m_EventTagActionWritePtr; + EventTagActionTransceivePtr m_EventTagActionTransceivePtr; + EventTagActionFormatPtr m_EventTagActionFormatPtr; + + protected: + nfc_tag_h handle; + std::vector props; + virtual void OnRequestReceived(const EventTagActionReadPtr& event); + virtual void OnRequestReceived(const EventTagActionWritePtr& event); + virtual void OnRequestReceived(const EventTagActionTransceivePtr& event); + virtual void OnRequestReceived(const EventTagActionFormatPtr& event); +}; + + +} +} +} + +#endif /* _NFCTAG_H_ */ diff --git a/src/platform/Tizen/NFC/NFCTagMifareClassic.cpp b/src/platform/Tizen/NFC/NFCTagMifareClassic.cpp new file mode 100755 index 0000000..636ffff --- /dev/null +++ b/src/platform/Tizen/NFC/NFCTagMifareClassic.cpp @@ -0,0 +1,428 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#include + +#include + +#include "NFCTagMifareClassic.h" +#include "NFCUtil.h" + +#include + +namespace TizenApis { +namespace Platform { +namespace NFC { + +using namespace Api::NFC; +using namespace WrtDeviceApis; +namespace +{ + /** + * Callback method called by platform as interval time. + * @param event_type Platform magnetic evet type + * @param event Platform sensor event data + * @param this_ User data pointer. + */ + static void MifareClassicAuthenticateWithKeyACallback(nfc_error_e result , void * data) { + LogDebug("Callback MifareClassicAuthenticateWithKeyACallback. result : " << result); + if (data) { + ((NFCTagMifareClassic *)data)->authenticateWithKeyAManualAnswer((int) result); + } else { + LogDebug("Error! MifareClassicAuthenticateWithKeyACallback is Null."); + } + } + + static void MifareClassicAuthenticateWithKeyBCallback(nfc_error_e result , void * data) { + LogDebug("Callback MifareClassicAuthenticateWithKeyBCallback. result : " << result); + if (data) { + ((NFCTagMifareClassic *)data)->authenticateWithKeyBManualAnswer((int)result); + } else { + LogDebug("Error! MifareClassicAuthenticateWithKeyBCallback is Null."); + } + } + + static void MifareClassicReadBlockCallback(nfc_error_e result , unsigned char * buffer, int buffer_size, void * data) { + LogDebug("Callback MifareClassicReadBlockCallback. result : " << result); + if (data) { + NFCUtil Util; + + ((NFCTagMifareClassic *)data)->readBlockManualAnswer((int)result, Util.toVector(buffer, buffer_size)); + } else { + LogDebug("Error! MifareClassicReadBlockCallback is Null."); + } + } + + static void MifareClassicWriteBlockCallback(nfc_error_e result , void * data) { + LogDebug("Callback MifareClassicAuthenticateWithKeyACallback. result : " << result); + if (data) { + ((NFCTagMifareClassic *)data)->writeBlockManualAnswer((int)result); + } else { + LogDebug("Error! MifareClassicAuthenticateWithKeyACallback is Null."); + } + } + + static void MifareClassicIncrementBlockValueCallback(nfc_error_e result , void * data) { + LogDebug("Callback MifareClassicIncrementBlockValueCallback. result : " << result); + if (data) { + ((NFCTagMifareClassic *)data)->incrementBlockValueManualAnswer((int)result); + } else { + LogDebug("Error! MifareClassicIncrementBlockValueCallback is Null."); + } + } + + static void MifareClassicDecrementBlockValueCallback(nfc_error_e result , void * data) { + LogDebug("Callback MifareClassicDecrementBlockValueCallback. result : " << result); + if (data) { + ((NFCTagMifareClassic *)data)->decrementBlockValueManualAnswer((int)result ); + } else { + LogDebug("Error! MifareClassicDecrementBlockValueCallback is Null."); + } + } + + static void MifareClassicTransferManualAnswerCallback(nfc_error_e result , void * data) { + LogDebug("Callback MifareClassicTransferManualAnswerCallback. result : " << result); + if (data) { + ((NFCTagMifareClassic *)data)->transferManualAnswer((int)result ); + } else { + LogDebug("Error! MifareClassicTransferManualAnswerCallback is Null."); + } + } + + static void MifareClassicRestoreManualAnswerCallback(nfc_error_e result , void * data) { + LogDebug("Callback MifareClassicRestoreCallback. result : " << result); + if (data) { + ((NFCTagMifareClassic *)data)->restoreManualAnswer((int)result ); + } else { + LogDebug("Error! MifareClassicRestoreCallback is Null."); + } + } +}//private namespace + +NFCTagMifareClassic::NFCTagMifareClassic(void *tagHandle) +{ + LogDebug("entered"); + + if (tagHandle == NULL) + ThrowMsg(Commons::PlatformException, "Tag Handler is Null Pointer."); + + handle = (nfc_tag_h)tagHandle; +} + +NFCTagMifareClassic::~NFCTagMifareClassic() +{ + LogDebug("entered"); + handle = NULL; +} + +void NFCTagMifareClassic::authenticateWithKeyA(const EventTagMifareClassicAuthenticateWithKeyAPtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTagMifareClassic::authenticateWithKeyB(const EventTagMifareClassicAuthenticateWithKeyBPtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTagMifareClassic::readBlock(const EventTagMifareClassicReadBlockPtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTagMifareClassic::writeBlock(const EventTagMifareClassicWriteBlockPtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTagMifareClassic::incrementBlockValue(const EventTagMifareClassicIncrementBlockValuePtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTagMifareClassic::decrementBlockValue(const EventTagMifareClassicDecrementBlockValuePtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} +void NFCTagMifareClassic::transfer(const EventTagMifareClassicTransferPtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTagMifareClassic::restore(const EventTagMifareClassicRestorePtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTagMifareClassic::authenticateWithKeyAManualAnswer(int result ) +{ + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagMifareClassicAuthenticateWithKeyAPtr->setResult(TRUE); + } else { + m_EventTagMifareClassicAuthenticateWithKeyAPtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagMifareClassicAuthenticateWithKeyAPtr); +} + +void NFCTagMifareClassic::authenticateWithKeyBManualAnswer(int result ) +{ + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagMifareClassicAuthenticateWithKeyBPtr->setResult(TRUE); + } else { + m_EventTagMifareClassicAuthenticateWithKeyBPtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagMifareClassicAuthenticateWithKeyBPtr); +} + +void NFCTagMifareClassic::readBlockManualAnswer(int result , std::vector data ) +{ + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagMifareClassicReadBlockPtr->setResult(TRUE); + m_EventTagMifareClassicReadBlockPtr->setBlockData(data); + } else { + m_EventTagMifareClassicReadBlockPtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagMifareClassicReadBlockPtr); +} + +void NFCTagMifareClassic::writeBlockManualAnswer(int result ) +{ + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagMifareClassicWriteBlockPtr->setResult(TRUE); + } else { + m_EventTagMifareClassicWriteBlockPtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagMifareClassicWriteBlockPtr); +} + +void NFCTagMifareClassic::incrementBlockValueManualAnswer(int result ) +{ + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagMifareClassicIncrementBlockValuePtr->setResult(TRUE); + } else { + m_EventTagMifareClassicIncrementBlockValuePtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagMifareClassicIncrementBlockValuePtr); +} + +void NFCTagMifareClassic::decrementBlockValueManualAnswer(int result ) +{ + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagMifareClassicDecrementBlockValuePtr->setResult(TRUE); + } else { + m_EventTagMifareClassicDecrementBlockValuePtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagMifareClassicDecrementBlockValuePtr); +} + +void NFCTagMifareClassic::transferManualAnswer(int result ) +{ + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagMifareClassicTransferPtr->setResult(TRUE); + } else { + m_EventTagMifareClassicTransferPtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagMifareClassicTransferPtr); +} + +void NFCTagMifareClassic::restoreManualAnswer(int result ) +{ + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagMifareClassicRestorePtr->setResult(TRUE); + } else { + m_EventTagMifareClassicRestorePtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagMifareClassicRestorePtr); +} + +void NFCTagMifareClassic::OnRequestReceived(const EventTagMifareClassicAuthenticateWithKeyAPtr& event) { + try { + event->switchToManualAnswer(); + + m_EventTagMifareClassicAuthenticateWithKeyAPtr = event; + NFCUtil Util; + + if( nfc_mifare_authenticate_with_keyA(handle, event->getSectorIndex(), Util.toCharPtr(event->getKey()), MifareClassicAuthenticateWithKeyACallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + +void NFCTagMifareClassic::OnRequestReceived(const EventTagMifareClassicAuthenticateWithKeyBPtr& event) { + try { + event->switchToManualAnswer(); + + m_EventTagMifareClassicAuthenticateWithKeyBPtr = event; + NFCUtil Util; + if( nfc_mifare_authenticate_with_keyB(handle, event->getSectorIndex(), Util.toCharPtr(event->getKey()), MifareClassicAuthenticateWithKeyBCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + +void NFCTagMifareClassic::OnRequestReceived(const EventTagMifareClassicReadBlockPtr& event) { + try { + event->switchToManualAnswer(); + + m_EventTagMifareClassicReadBlockPtr = event; + + if( nfc_mifare_read_block(handle, event->getIndex(), MifareClassicReadBlockCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + +void NFCTagMifareClassic::OnRequestReceived(const EventTagMifareClassicWriteBlockPtr& event) { + try { + event->switchToManualAnswer(); + + m_EventTagMifareClassicWriteBlockPtr = event; + + NFCUtil Util; + std::vector data = event->getBlockData(); + if( nfc_mifare_write_block(handle, event->getIndex(), Util.toCharPtr(data), data.size(), MifareClassicWriteBlockCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + +void NFCTagMifareClassic::OnRequestReceived(const EventTagMifareClassicIncrementBlockValuePtr& event) { + try { + event->switchToManualAnswer(); + + m_EventTagMifareClassicIncrementBlockValuePtr = event; + + if( nfc_mifare_increment(handle, event->getIndex(), event->getValue(), MifareClassicIncrementBlockValueCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + +void NFCTagMifareClassic::OnRequestReceived(const EventTagMifareClassicDecrementBlockValuePtr& event) { + try { + event->switchToManualAnswer(); + + m_EventTagMifareClassicDecrementBlockValuePtr = event; + + NFCUtil Util; + if( nfc_mifare_decrement(handle, event->getIndex(), event->getValue(), MifareClassicDecrementBlockValueCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + +void NFCTagMifareClassic::OnRequestReceived(const EventTagMifareClassicTransferPtr& event) { + try { + event->switchToManualAnswer(); + + m_EventTagMifareClassicTransferPtr = event; + + if( nfc_mifare_transfer(handle, event->getIndex(), MifareClassicTransferManualAnswerCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + +void NFCTagMifareClassic::OnRequestReceived(const EventTagMifareClassicRestorePtr& event) { + try { + event->switchToManualAnswer(); + + m_EventTagMifareClassicRestorePtr = event; + + if( nfc_mifare_restore(handle, event->getIndex(), MifareClassicRestoreManualAnswerCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + +} +} +} diff --git a/src/platform/Tizen/NFC/NFCTagMifareClassic.h b/src/platform/Tizen/NFC/NFCTagMifareClassic.h new file mode 100755 index 0000000..114b77f --- /dev/null +++ b/src/platform/Tizen/NFC/NFCTagMifareClassic.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _NFCTAGMIFARECLASSIC_H_ +#define _NFCTAGMIFARECLASSIC_H_ + +#include + +using namespace TizenApis::Api::NFC; + +namespace TizenApis { +namespace Platform { +namespace NFC { + +class NFCTagMifareClassic : public INFCTagMifareClassic +{ + friend class NFCFactory; + public: + NFCTagMifareClassic(void *tagHandle); + virtual ~NFCTagMifareClassic(); + + virtual void authenticateWithKeyA(const EventTagMifareClassicAuthenticateWithKeyAPtr& event); + virtual void authenticateWithKeyB(const EventTagMifareClassicAuthenticateWithKeyBPtr& event); + virtual void readBlock(const EventTagMifareClassicReadBlockPtr& event); + virtual void writeBlock(const EventTagMifareClassicWriteBlockPtr& event); + virtual void incrementBlockValue(const EventTagMifareClassicIncrementBlockValuePtr& event); + virtual void decrementBlockValue(const EventTagMifareClassicDecrementBlockValuePtr& event); + virtual void transfer(const EventTagMifareClassicTransferPtr& event); + virtual void restore(const EventTagMifareClassicRestorePtr& event); + virtual void authenticateWithKeyAManualAnswer(int result); + virtual void authenticateWithKeyBManualAnswer(int result); + virtual void readBlockManualAnswer(int result , std::vector data); + virtual void writeBlockManualAnswer(int result); + virtual void incrementBlockValueManualAnswer(int result); + virtual void decrementBlockValueManualAnswer(int result); + virtual void transferManualAnswer(int result); + virtual void restoreManualAnswer(int result); + + protected: + virtual void OnRequestReceived(const EventTagMifareClassicAuthenticateWithKeyAPtr& event); + virtual void OnRequestReceived(const EventTagMifareClassicAuthenticateWithKeyBPtr& event); + virtual void OnRequestReceived(const EventTagMifareClassicReadBlockPtr& event); + virtual void OnRequestReceived(const EventTagMifareClassicWriteBlockPtr& event); + virtual void OnRequestReceived(const EventTagMifareClassicIncrementBlockValuePtr& event); + virtual void OnRequestReceived(const EventTagMifareClassicDecrementBlockValuePtr& event); + virtual void OnRequestReceived(const EventTagMifareClassicTransferPtr& event); + virtual void OnRequestReceived(const EventTagMifareClassicRestorePtr& event); + private: + EventTagMifareClassicAuthenticateWithKeyAPtr m_EventTagMifareClassicAuthenticateWithKeyAPtr; + EventTagMifareClassicAuthenticateWithKeyBPtr m_EventTagMifareClassicAuthenticateWithKeyBPtr; + EventTagMifareClassicReadBlockPtr m_EventTagMifareClassicReadBlockPtr; + EventTagMifareClassicWriteBlockPtr m_EventTagMifareClassicWriteBlockPtr; + EventTagMifareClassicIncrementBlockValuePtr m_EventTagMifareClassicIncrementBlockValuePtr; + EventTagMifareClassicDecrementBlockValuePtr m_EventTagMifareClassicDecrementBlockValuePtr; + EventTagMifareClassicTransferPtr m_EventTagMifareClassicTransferPtr; + EventTagMifareClassicRestorePtr m_EventTagMifareClassicRestorePtr; +}; + +} +} +} + +#endif /* _NFCTAGMIFARECLASSIC_H_ */ diff --git a/src/platform/Tizen/NFC/NFCTagMifareUltra.cpp b/src/platform/Tizen/NFC/NFCTagMifareUltra.cpp new file mode 100755 index 0000000..eddd85e --- /dev/null +++ b/src/platform/Tizen/NFC/NFCTagMifareUltra.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#include + +#include + +#include "NFCTagMifareUltra.h" +#include "NFCUtil.h" +#include + +namespace TizenApis { +namespace Platform { +namespace NFC { + +using namespace Api::NFC; +using namespace WrtDeviceApis; + +namespace +{ + /** + * Callback method called by platform as interval time. + * @param event_type Platform magnetic evet type + * @param event Platform sensor event data + * @param this_ User data pointer. + */ + static void MifareUltraReadPageCallback(nfc_error_e result , unsigned char * buffer, int buffer_size, void * data) { + LogDebug("Callback MifareUltraReadPageCallback."); + if (data) { + NFCUtil Util; + + ((NFCTagMifareUltra *)data)->readPageManualAnswer((int)result , Util.toVector(buffer, buffer_size)); + + } else { + LogDebug("Error! MifareUltraReadPageCallback is Null."); + } + } + + static void MifareUltraWritePageCallback(nfc_error_e result , void * data) { + LogDebug("Callback MifareUltraWritePageCallback."); + if (data) { + ((NFCTagMifareUltra *)data)->writePageManualAnswer((int)result); + } else { + LogDebug("Error! MifareUltraAuthenticateWithKeyACallback is Null."); + } + } + +}//private namespace + +NFCTagMifareUltra::NFCTagMifareUltra(void *tagHandle) +{ + LogDebug("entered"); + if (tagHandle == NULL) + ThrowMsg(Commons::PlatformException, "Tag Handler is Null Pointer."); + handle = (nfc_tag_h)tagHandle; +} + +NFCTagMifareUltra::~NFCTagMifareUltra() +{ + LogDebug("entered"); + handle = NULL; +} + +void NFCTagMifareUltra::readPage(const EventTagMifareUltraReadPagePtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTagMifareUltra::writePage(const EventTagMifareUltraWritePagePtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTagMifareUltra::readPageManualAnswer(int result , std::vector data) +{ + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagMifareUltraReadPagePtr->setResult(TRUE); + m_EventTagMifareUltraReadPagePtr->setReadPageResult(data); + } else { + m_EventTagMifareUltraReadPagePtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagMifareUltraReadPagePtr); +} + +void NFCTagMifareUltra::writePageManualAnswer(int result) +{ + LogDebug("Enter result : " << result); + + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagMifareUltraWritePagePtr->setResult(TRUE); + } else { + m_EventTagMifareUltraWritePagePtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTagMifareUltraWritePagePtr); +} + +void NFCTagMifareUltra::OnRequestReceived(const EventTagMifareUltraReadPagePtr& event) { + LogDebug("EventTagMifareUltraReadPagePtr OnRequestReceived index : " << event->getIndex()); + + try { + event->switchToManualAnswer(); + + m_EventTagMifareUltraReadPagePtr = event; + + if( nfc_mifare_read_page(handle, event->getIndex(), MifareUltraReadPageCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + +void NFCTagMifareUltra::OnRequestReceived(const EventTagMifareUltraWritePagePtr& event) { + try { + event->switchToManualAnswer(); + + m_EventTagMifareUltraWritePagePtr = event; + + NFCUtil Util; + std::vector data = event->getPageForWriting(); + if( nfc_mifare_write_page(handle, event->getIndex(), Util.toCharPtr(data), data.size(), MifareUltraWritePageCallback, this) != NFC_ERROR_NONE ) + { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } + catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } + +} + +} +} +} diff --git a/src/platform/Tizen/NFC/NFCTagMifareUltra.h b/src/platform/Tizen/NFC/NFCTagMifareUltra.h new file mode 100755 index 0000000..3b3c552 --- /dev/null +++ b/src/platform/Tizen/NFC/NFCTagMifareUltra.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _NFCTAGMIFAREULTRA_H_ +#define _NFCTAGMIFAREULTRA_H_ + +#include + +using namespace TizenApis::Api::NFC; + +namespace TizenApis { +namespace Platform { +namespace NFC { + +class NFCTagMifareUltra : public INFCTagMifareUltra +{ + friend class NFCFactory; + public: + NFCTagMifareUltra(void *tagHandle); + virtual ~NFCTagMifareUltra(); + + virtual void readPage(const EventTagMifareUltraReadPagePtr& event); + virtual void writePage(const EventTagMifareUltraWritePagePtr& event); + virtual void readPageManualAnswer(int result , std::vector data); + virtual void writePageManualAnswer(int result); + + protected: + virtual void OnRequestReceived(const EventTagMifareUltraReadPagePtr& event); + virtual void OnRequestReceived(const EventTagMifareUltraWritePagePtr& event); + private: + EventTagMifareUltraReadPagePtr m_EventTagMifareUltraReadPagePtr; + EventTagMifareUltraWritePagePtr m_EventTagMifareUltraWritePagePtr; +}; + } +} +} + +#endif /* _NFCTAGMIFAREULTRA_H_ */ diff --git a/src/platform/Tizen/NFC/NFCTarget.cpp b/src/platform/Tizen/NFC/NFCTarget.cpp new file mode 100755 index 0000000..c8bb234 --- /dev/null +++ b/src/platform/Tizen/NFC/NFCTarget.cpp @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#include + +#include + +#include "NFCTarget.h" +#include "NFCUtil.h" + +namespace TizenApis { +namespace Platform { +namespace NFC { + +using namespace Api::NFC; +using namespace WrtDeviceApis; + +namespace +{ + /** + * Callback method called by platform as interval time. + * @param event_type Platform magnetic evet type + * @param event Platform sensor event data + * @param this_ User data pointer. + */ + static void TargetReceivedCallback(nfc_p2p_target_h target, nfc_ndef_message_h message, void *user_data) { + LogDebug("Callback TargetReceivedCallback."); + if (user_data) { + unsigned char *UrawData; + int size; + if (nfc_ndef_message_get_rawdata(message, &UrawData, &size) != NFC_ERROR_NONE) { + LogError("Can't get rawdata of message"); + return; + } + + NFCUtil Util; + ((NFCTarget *)user_data)->receiveNdef(Util.toVector(UrawData, size)); + + + } else { + LogDebug("Error! TargetReceivedCallback is Null."); + } + } + + static void TargetSentCallback(nfc_error_e result, void *user_data) { + LogDebug("Callback TargetSentCallback."); + if (user_data) { + ((NFCTarget *)user_data)->sendNDEFManualAnswer((unsigned int)result); + + } else { + LogDebug("Error! TargetSentCallback is Null."); + } + } +}//private namespace + +NFCTarget::NFCTarget(void *targetHandle) +{ + LogDebug("entered"); + + if (targetHandle == NULL) + ThrowMsg(Commons::PlatformException, "Taretg Handler is Null Pointer."); + + handle = (nfc_p2p_target_h)targetHandle; + LogDebug("handle:"<messageData) { + LogDebug("Enter"); + if (m_isSetReceiveListenter == true) { + EventTargetActionReceivePtr event(new EventTargetActionReceive()); + event->setReadNdefResult(messageData); + m_emitter->emit(event); + } +} + +void NFCTarget::unsetReceiveNDEFListener() { + LogDebug("Enter"); + if (m_isSetReceiveListenter == true) { + nfc_p2p_unset_data_received_cb(handle); + LogDebug("Success to unset Listener"); + } else { + LogDebug("No set Listener"); + } + m_isSetReceiveListenter = false; +} + +void NFCTarget::sendNDEF(const EventTargetActionSendPtr& event) { + LogDebug("Enter"); + EventRequestReceiver::PostRequest(event); +} + +void NFCTarget::sendNDEFManualAnswer(unsigned int result) { + LogDebug("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTargetActionSendPtr->setResult(TRUE); + + } else { + m_EventTargetActionSendPtr->setResult(FALSE); + } + EventRequestReceiver::ManualAnswer(m_EventTargetActionSendPtr); +} + +void NFCTarget::OnRequestReceived(const EventTargetActionSendPtr& event) { + LogDebug("Enter"); + try { + event->switchToManualAnswer(); + m_EventTargetActionSendPtr = event; + nfc_ndef_message_h message = (nfc_ndef_message_h)event->getMessageForSending(); + if( nfc_p2p_send(handle, message, TargetSentCallback, this) != NFC_ERROR_NONE ) { + ThrowMsg(Commons::UnknownException, "call back set error"); + } + } catch (const Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver::ManualAnswer(event); + } +} + +} +} +} diff --git a/src/platform/Tizen/NFC/NFCTarget.h b/src/platform/Tizen/NFC/NFCTarget.h new file mode 100755 index 0000000..1d1e9d4 --- /dev/null +++ b/src/platform/Tizen/NFC/NFCTarget.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _NFCTARGET_H_ +#define _NFCTARGET_H_ + +#include +#include + +using namespace TizenApis::Api::NFC; + +namespace TizenApis { +namespace Platform { +namespace NFC { + +class NFCTarget : public INFCTarget +{ + friend class NFCFactory; + public: + + NFCTarget(void *tagHandle); + virtual ~NFCTarget(); + + virtual void *getHandle(); + virtual void setReceiveNDEFListener(const EventTargetActionReceiveEmitterPtr& event); + virtual void receiveNdef(std::vectormessageData); + virtual void unsetReceiveNDEFListener(); + virtual void sendNDEF(const EventTargetActionSendPtr& event); + virtual void sendNDEFManualAnswer(unsigned int result); + protected: + nfc_p2p_target_h handle; + EventTargetActionReceiveEmitterPtr m_emitter; + bool m_isSetReceiveListenter; + EventTargetActionSendPtr m_EventTargetActionSendPtr; + virtual void OnRequestReceived(const EventTargetActionSendPtr& event); +}; + + +} +} +} + +#endif /* _NFCTARGET_H_ */ diff --git a/src/platform/Tizen/NFC/NFCUtil.cpp b/src/platform/Tizen/NFC/NFCUtil.cpp new file mode 100755 index 0000000..6bb6ad7 --- /dev/null +++ b/src/platform/Tizen/NFC/NFCUtil.cpp @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#include + +#include "NFCUtil.h" +#include +#include + + +namespace TizenApis { +namespace Platform { +namespace NFC { + +using namespace Api::NFC; + +std::vector NFCUtil::toVector(const unsigned char *ch, const int size) { + std::vector vec; + if (ch && (size > 0)) { + int i; + + for (i = 0; i < size; i++) + vec.push_back(ch[i]); + } + LogDebug("result:" << byteToString(ch, size)); + return vec; +} + +unsigned char *NFCUtil::toCharPtr(std::vector vec) { + if (vec.size() > 0) { + unsigned char * chr = (unsigned char *) malloc(vec.size() * sizeof(unsigned char)); + for (int i = 0; i < static_cast(vec.size()); i++) + chr[i] = vec.at(i); + + return chr; + } + + return NULL; +} + +char *NFCUtil::byteToString(std::vector buffer){ + static char localbuffer[255]; + memset(localbuffer, 0, 255); + memcpy(localbuffer, toCharPtr(buffer), buffer.size()); + return localbuffer; +} + +char *NFCUtil::byteToString(const unsigned char* buffer, const int size){ + static char localbuffer[255]; + memset(localbuffer, 0, 255); + memcpy(localbuffer, buffer, size); + return localbuffer; +} + +nfcTagType NFCUtil::convertTonfcTagType(const unsigned short type) { + switch (static_cast(type)) { + case NFC_GENERIC_PICC: + return NFC_TAGTYPE_GENERIC_PICC; + case NFC_ISO14443_A_PICC: + return NFC_TAGTYPE_ISO14443_A_PICC; + case NFC_ISO14443_4A_PICC: + return NFC_TAGTYPE_ISO14443_4A_PICC; + case NFC_ISO14443_3A_PICC: + return NFC_TAGTYPE_ISO14443_3A_PICC; + case NFC_MIFARE_MINI_PICC: + return NFC_TAGTYPE_MIFARE_MINI_PICC; + case NFC_MIFARE_1K_PICC: + return NFC_TAGTYPE_MIFARE_1K_PICC; + case NFC_MIFARE_4K_PICC: + return NFC_TAGTYPE_MIFARE_4K_PICC; + case NFC_MIFARE_ULTRA_PICC: + return NFC_TAGTYPE_MIFARE_ULTRA_PICC; + case NFC_MIFARE_DESFIRE_PICC: + return NFC_TAGTYPE_MIFARE_DESFIRE_PICC; + case NFC_ISO14443_B_PICC: + return NFC_TAGTYPE_ISO14443_B_PICC; + case NFC_ISO14443_4B_PICC: + return NFC_TAGTYPE_ISO14443_4B_PICC; + case NFC_ISO14443_BPRIME_PICC: + return NFC_TAGTYPE_ISO14443_BPRIME_PICC; + case NFC_FELICA_PICC: + return NFC_TAGTYPE_FELICA_PICC; + case NFC_JEWEL_PICC: + return NFC_TAGTYPE_JEWEL_PICC; + case NFC_ISO15693_PICC: + return NFC_TAGTYPE_ISO15693_PICC; + case NFC_UNKNOWN_TARGET: + default : + return NFC_TAGTYPE_UNKNOWN_TARGET; + } +} + +unsigned short NFCUtil::convertToTNF(nfcTNF tnf) { + switch (tnf) { + case NFC_TNF_EMPTY: + return static_cast(NFC_RECORD_TNF_EMPTY); + case NFC_TNF_WELL_KNOWN: + return static_cast(NFC_RECORD_TNF_WELL_KNOWN); + case NFC_TNF_MIME_MEDIA: + return static_cast(NFC_RECORD_TNF_MIME_MEDIA); + case NFC_TNF_URI: + return static_cast(NFC_RECORD_TNF_URI); + case NFC_TNF_EXTERNAL_RTD: + return static_cast(NFC_RECORD_TNF_EXTERNAL_RTD); + case NFC_TNF_UNKNOWN: + return static_cast(NFC_RECORD_TNF_UNKNOWN); + case NFC_TNF_UNCHAGNED: + return static_cast(NFC_RECORD_TNF_UNCHAGNED); + } +} + +nfcTNF NFCUtil::convertTonfcTNF(unsigned short tnf) { + switch (static_cast(tnf)) { + case NFC_RECORD_TNF_EMPTY: + return NFC_TNF_EMPTY; + case NFC_RECORD_TNF_WELL_KNOWN: + return NFC_TNF_WELL_KNOWN; + case NFC_RECORD_TNF_MIME_MEDIA: + return NFC_TNF_MIME_MEDIA; + case NFC_RECORD_TNF_URI: + return NFC_TNF_URI; + case NFC_RECORD_TNF_EXTERNAL_RTD: + return NFC_TNF_EXTERNAL_RTD; + case NFC_RECORD_TNF_UNKNOWN: + return NFC_TNF_UNKNOWN; + case NFC_RECORD_TNF_UNCHAGNED: + return NFC_TNF_UNCHAGNED; + } +} + +} +} +} diff --git a/src/platform/Tizen/NFC/NFCUtil.h b/src/platform/Tizen/NFC/NFCUtil.h new file mode 100755 index 0000000..296bfea --- /dev/null +++ b/src/platform/Tizen/NFC/NFCUtil.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _NFCUTIL_H_ +#define _NFCUTIL_H_ + +#include +#include +#include + +using namespace TizenApis::Api::NFC; + +namespace TizenApis { +namespace Platform { +namespace NFC { + +class NFCUtil +{ + + public: + NFCUtil() {} + virtual ~NFCUtil() {} + std::vector toVector(const unsigned char *ch, const int size); + unsigned char *toCharPtr(std::vector vec) ; + char *byteToString(const unsigned char* buffer, const int size); + char *byteToString(std::vector buffer); + nfcTagType convertTonfcTagType(const unsigned short type); + unsigned short convertToTNF(nfcTNF tnf); + nfcTNF convertTonfcTNF(unsigned short tnf); + +}; + +} +} +} + +#endif /* _NFCUTIL_H_ */ diff --git a/src/platform/Tizen/NFC/NdefMessage.cpp b/src/platform/Tizen/NFC/NdefMessage.cpp new file mode 100755 index 0000000..b6e86f1 --- /dev/null +++ b/src/platform/Tizen/NFC/NdefMessage.cpp @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include + +#include + +#include "NdefMessage.h" +#include "NFCUtil.h" + +namespace TizenApis { +namespace Platform { +namespace NFC { + +using namespace Api::NFC; +using namespace WrtDeviceApis::Commons; + +NdefMessage::NdefMessage() +{ + LogDebug("entered"); + if (nfc_ndef_message_create(&handle) != NFC_ERROR_NONE) { + handle = NULL; + ThrowMsg(PlatformException, "Can't create Ndef Message"); + } +} + +NdefMessage::NdefMessage(void *messageHandle) +{ + LogDebug("entered"); + + if (messageHandle == NULL) { + handle = NULL; + ThrowMsg(PlatformException, "Message Handler is Null Pointer."); + } + + handle = static_cast(messageHandle); +} + +NdefMessage::NdefMessage(const std::vector ndefRcords) +{ + LogDebug("entered"); + + if (nfc_ndef_message_create(&handle) != NFC_ERROR_NONE) { + handle = NULL; + ThrowMsg(PlatformException, "Can't create Ndef Message"); + } + + for (int i = 0 ; i < static_cast(ndefRcords.size()); i++) { + nfc_ndef_record_h appendRecord; + if (!_copyNDEFRecord((nfc_ndef_record_h*)&ndefRcords[i], &appendRecord)) { + LogDebug("copyNDEFRecord fail!"); + ThrowMsg(PlatformException, "Can't copy Record"); + } + + if (nfc_ndef_message_append_record(handle, appendRecord) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't create Ndef Message"); + } +} + +NdefMessage::NdefMessage(const std::vector rawdata) +{ + LogDebug("entered"); + + NFCUtil Util; + unsigned char *Urawdata = Util.toCharPtr(rawdata); + if (nfc_ndef_message_create_from_rawdata(&handle, Urawdata, rawdata.size()) != NFC_ERROR_NONE) { + handle = NULL; + free(Urawdata); + ThrowMsg(PlatformException, "Can't create Ndef Message"); + } + + free(Urawdata); +} + +NdefMessage::~NdefMessage() +{ + LogDebug("entered"); + if (handle != NULL) + nfc_ndef_message_destroy(handle); +} + +bool NdefMessage::_copyNDEFRecord(nfc_ndef_record_h *srcHandle, nfc_ndef_record_h *destHandle) { + nfc_record_tnf_e tnf; + unsigned char *typeName, *id, *payload; + int typeSize, idSize, payloadSize; + + if (nfc_ndef_record_get_tnf(*srcHandle, &tnf) != NFC_ERROR_NONE) + return false; + + if (nfc_ndef_record_get_type(*srcHandle, &typeName, &typeSize) != NFC_ERROR_NONE) + return false; + + if (nfc_ndef_record_get_id(*srcHandle, &id, &idSize) != NFC_ERROR_NONE) + return false; + + if (nfc_ndef_record_get_payload(*srcHandle, &payload, &payloadSize) != NFC_ERROR_NONE) + return false; + + if (nfc_ndef_record_create(destHandle, tnf, typeName, typeSize, id, idSize, payload, payloadSize) != NFC_ERROR_NONE) + return false; + + return true; +} + +void *NdefMessage::getHandle() { + return (void *)handle; +} + +long NdefMessage::getRecordCount() { + int count; + if (nfc_ndef_message_get_record_count(handle, &count) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get Record Count"); + + LogDebug("record Count : " << count); + return static_cast(count); +} + +std::vector NdefMessage::toByte() { + unsigned char *UrawData; + int size; + + if (nfc_ndef_message_get_rawdata(handle, &UrawData, &size) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get serial bytes of NDEF message"); + + LogDebug(UrawData); + NFCUtil Util; + return Util.toVector(UrawData, size); +} + +NdefRecordData NdefMessage::getNDEFRecord(const long index) { + nfc_ndef_record_h recordHandle; + if (nfc_ndef_message_get_record(handle, static_cast(index), &recordHandle) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get Ndef Record"); + + NdefRecordData recordData; + + nfc_record_tnf_e tnf; + unsigned char *typeName, *id, *payload; + int typeSize, idSize, payloadSize; + NFCUtil Util; + + if (nfc_ndef_record_get_tnf(recordHandle, &tnf) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get record's tnf"); + + if (nfc_ndef_record_get_type(recordHandle, &typeName, &typeSize) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get record's type"); + + if (nfc_ndef_record_get_id(recordHandle, &id, &idSize) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get record's id"); + + if (nfc_ndef_record_get_payload(recordHandle, &payload, &payloadSize) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get record's payload"); + + LogDebug("tnf : " <(tnf)); + recordData.properties.typeName = Util.toVector(typeName, typeSize); + recordData.properties.id = Util.toVector(id, idSize); + recordData.payload = Util.toVector(payload, payloadSize); + + return recordData; +} + +bool NdefMessage::insertNDEFRecord(const long index, const void *recordHandle) { + nfc_ndef_record_h insertRecord; + if (!_copyNDEFRecord((nfc_ndef_record_h *)&recordHandle, &insertRecord)) { + LogDebug("copyNDEFRecord fail!"); + ThrowMsg(PlatformException, "Can't copy Record"); + } + + if (nfc_ndef_message_insert_record(handle, static_cast(index), insertRecord) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't insert ndef Record"); + + return TRUE; +} + +bool NdefMessage::appendNDEFRecord(const void *recordHandle) { + nfc_ndef_record_h appendRecord; + if (!_copyNDEFRecord((nfc_ndef_record_h *)&recordHandle, &appendRecord)) { + LogDebug("copyNDEFRecord fail!"); + ThrowMsg(PlatformException, "Can't copy Record"); + } + + if (nfc_ndef_message_append_record(handle, appendRecord) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't append ndef Record"); + + return TRUE; +} + +bool NdefMessage::removeNDEFRecord(const long index) { + if (nfc_ndef_message_remove_record(handle, static_cast(index)) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't remove ndef Record"); + + return TRUE; +} + +} +} +} diff --git a/src/platform/Tizen/NFC/NdefMessage.h b/src/platform/Tizen/NFC/NdefMessage.h new file mode 100755 index 0000000..364209c --- /dev/null +++ b/src/platform/Tizen/NFC/NdefMessage.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _NDEFMESSAGE_H_ +#define _NDEFMESSAGE_H_ + +#include +#include + +using namespace TizenApis::Api::NFC; + +namespace TizenApis { +namespace Platform { +namespace NFC { + +class NdefMessage : public INdefMessage +{ + friend class NFCFactory; + public: + NdefMessage(); + NdefMessage(void *messageHandle); + NdefMessage(const std::vector ndefRcords); + NdefMessage(const std::vector rawdata); + virtual ~NdefMessage(); + + virtual void *getHandle(); + virtual long getRecordCount(); + virtual std::vector toByte(); + virtual NdefRecordData getNDEFRecord(const long index); + virtual bool insertNDEFRecord(const long index, const void *recordHandle); + virtual bool appendNDEFRecord(const void *recordHandle); + virtual bool removeNDEFRecord(const long index); + + private: + nfc_ndef_message_h handle; + bool _copyNDEFRecord(nfc_ndef_record_h *srcHandle, nfc_ndef_record_h *destHandle); +}; + +} +} +} + +#endif /* _NDEFMESSAGE_H_ */ diff --git a/src/platform/Tizen/NFC/NdefRecord.cpp b/src/platform/Tizen/NFC/NdefRecord.cpp new file mode 100755 index 0000000..5fdc93e --- /dev/null +++ b/src/platform/Tizen/NFC/NdefRecord.cpp @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#include +#include + +#include "NdefRecord.h" +#include "NFCUtil.h" + +namespace TizenApis { +namespace Platform { +namespace NFC { + +using namespace Api::NFC; +using namespace WrtDeviceApis::Commons; + +NdefRecord::NdefRecord(const NdefRecordProperties &ndefRecordProperties, std::vector payload) +{ + LogDebug("entered"); + + NFCUtil Util; + + unsigned char * recordPayload = Util.toCharPtr(payload); + unsigned char * typeName = Util.toCharPtr(ndefRecordProperties.typeName); + unsigned char * id = Util.toCharPtr(ndefRecordProperties.id); + + LogDebug("typeName : " << Util.byteToString(typeName, ndefRecordProperties.typeName.size())); + int result = nfc_ndef_record_create(&handle, static_cast(Util.convertToTNF(ndefRecordProperties.tnf)), typeName, ndefRecordProperties.typeName.size(), + id, ndefRecordProperties.id.size(), recordPayload, payload.size()) ; + + free(recordPayload); + free(typeName); + free(id); + + if (result != NFC_ERROR_NONE) { + handle = NULL; + ThrowMsg(PlatformException, "Can't create Ndef Record"); + } +} + +NdefRecord::NdefRecord(void *recordhandle) +{ + LogDebug("entered"); + + handle = (nfc_ndef_record_h)recordhandle; + + if (recordhandle == NULL) + ThrowMsg(PlatformException, "Record Handler is Null Pointer."); +} + +NdefRecord::NdefRecord(const std::string &text, const std::string &langCode, const short encodeType) +{ + LogDebug("entered"); + + if (nfc_ndef_record_create_text(&handle, text.c_str(), langCode.c_str(), _convertToEncodeType(static_cast(encodeType))) != NFC_ERROR_NONE) { + handle = NULL; + ThrowMsg(PlatformException, "Can't create Ndef Text Record"); + } +} + +NdefRecord::NdefRecord(const std::string &uri) +{ + LogDebug("entered"); + + if (nfc_ndef_record_create_uri(&handle, uri.c_str()) != NFC_ERROR_NONE) { + handle = NULL; + ThrowMsg(PlatformException, "Can't create Ndef Uri Record"); + } +} + +NdefRecord::NdefRecord(const std::string &mimeType, const std::vector data) +{ + LogDebug("entered"); + + NFCUtil Util; + + if (nfc_ndef_record_create_mime(&handle, mimeType.c_str(), Util.toCharPtr(data),static_cast(data.size())) != NFC_ERROR_NONE) { + handle = NULL; + ThrowMsg(PlatformException, "Can't create Ndef Mime Record"); + } +} + +NdefRecord::~NdefRecord() +{ + LogDebug("entered"); + if (handle != NULL) + nfc_ndef_record_destroy(handle); +} + +nfc_encode_type_e NdefRecord::_convertToEncodeType(const nfcTextEncodeUTF type) { + switch(type) { + case NFC_TEXT_ENCODE_UTF_8: + return NFC_ENCODE_UTF_8; + case NFC_TEXT_ENCODE_UTF_16: + return NFC_ENCODE_UTF_16; + } +} + +nfcTextEncodeUTF NdefRecord::_convertToNfcEncodeType(const nfc_encode_type_e type) { + switch(type) { + case NFC_ENCODE_UTF_8: + return NFC_TEXT_ENCODE_UTF_8; + case NFC_ENCODE_UTF_16: + return NFC_TEXT_ENCODE_UTF_16; + } +} + +void *NdefRecord::getHandle() { + return (void *)handle; +} + +NdefRecordProperties NdefRecord::getNDEFRecordProperties() { + LogDebug("entered"); + NdefRecordProperties props; + nfc_record_tnf_e tnf; + unsigned char *typeName, *id; + int typeSize, idSize; + NFCUtil Util; + + if (nfc_ndef_record_get_tnf(handle, &tnf) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get record's tnf"); + + if (nfc_ndef_record_get_type(handle, &typeName, &typeSize) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get record's type"); + + if (nfc_ndef_record_get_id(handle, &id, &idSize) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get record's id"); + + props.tnf = Util.convertTonfcTNF(static_cast(tnf)); + LogDebug("tnf : " << props.tnf); + props.typeName = Util.toVector(typeName, typeSize); + props.id = Util.toVector(id, idSize); + LogDebug("typeName : " << Util.byteToString(props.typeName)); + + return props; +} + +bool NdefRecord::getText(char **text) { + LogDebug("entered"); + + int result = nfc_ndef_record_get_text(handle, text); + if (result == NFC_ERROR_INVALID_RECORD_TYPE) + return false; + if (result != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get text of record"); + + LogDebug("text : " << *text); + return true; +} + +bool NdefRecord::getLangCode(char **landCode) { + LogDebug("entered"); + + int result = nfc_ndef_record_get_langcode(handle, landCode); + if (result == NFC_ERROR_INVALID_RECORD_TYPE) + return false; + if (result != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get langcode of record"); + + LogDebug("landCode : " << *landCode); + return true; +} +bool NdefRecord::getEncodeType(nfcTextEncodeUTF *encodeType) { + LogDebug("entered"); + + nfc_encode_type_e type; + int result = nfc_ndef_record_get_encode_type(handle, &type); + if (result == NFC_ERROR_INVALID_RECORD_TYPE) + return false; + if (result != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get encode type of record"); + + *encodeType = _convertToNfcEncodeType(type); + LogDebug("encodeType : " << *encodeType); + return true; +} + +bool NdefRecord::getUri(char **uri) { + LogDebug("entered"); + int result = nfc_ndef_record_get_uri(handle, uri); + if (result == NFC_ERROR_INVALID_RECORD_TYPE) + return false; + if (result != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get uri of record"); + + LogDebug("uri : " << *uri); + return true; +} + +bool NdefRecord::getMimeType(char **mimeType) { + LogDebug("entered"); + int result = nfc_ndef_record_get_mime_type(handle, mimeType); + if (result == NFC_ERROR_INVALID_RECORD_TYPE) + return false; + if (result != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get text of record"); + + LogDebug("mimeType : " << *mimeType); + return true; +} +std::vector NdefRecord::getPayload() { + LogDebug("entered"); + int size; + unsigned char *recordbuffer; + + if (nfc_ndef_record_get_payload(handle, &recordbuffer, &size) != NFC_ERROR_NONE) + ThrowMsg(PlatformException, "Can't get record's payload"); + + NFCUtil Util; + LogDebug("payload : " << Util.byteToString(recordbuffer, size)); + return Util.toVector(recordbuffer, size); +} + +} +} +} diff --git a/src/platform/Tizen/NFC/NdefRecord.h b/src/platform/Tizen/NFC/NdefRecord.h new file mode 100755 index 0000000..a1a9189 --- /dev/null +++ b/src/platform/Tizen/NFC/NdefRecord.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _NDEFRECORD_H_ +#define _NDEFRECORD_H_ + +#include +#include +#include + +using namespace TizenApis::Api::NFC; + +namespace TizenApis { +namespace Platform { +namespace NFC { + +class NdefRecord : public INdefRecord +{ + friend class NFCFactory; + public: + NdefRecord(const NdefRecordProperties &ndefRecordProperties, std::vector payload); + NdefRecord(void *recordhandle); + NdefRecord(const std::string &text, const std::string &langCode, const short encodeType); + NdefRecord(const std::string &uri); + NdefRecord(const std::string &mimeType, const std::vector data); + virtual ~NdefRecord(); + virtual void *getHandle(); + virtual NdefRecordProperties getNDEFRecordProperties(); + virtual std::vector getPayload(); + virtual bool getText(char **text); + virtual bool getLangCode(char **landCode); + virtual bool getEncodeType(nfcTextEncodeUTF *encodeType); + virtual bool getUri(char **uri); + virtual bool getMimeType(char **mimeType); + + private: + nfc_ndef_record_h handle; + nfc_encode_type_e _convertToEncodeType(const nfcTextEncodeUTF type); + nfcTextEncodeUTF _convertToNfcEncodeType(const nfc_encode_type_e type); +}; + +} +} +} + +#endif /* _NDEFRECORD_H_ */ diff --git a/src/platform/Tizen/NFC/config.cmake b/src/platform/Tizen/NFC/config.cmake new file mode 100755 index 0000000..4bc85b2 --- /dev/null +++ b/src/platform/Tizen/NFC/config.cmake @@ -0,0 +1,25 @@ +get_current_path() + +pkg_search_module(capi-network-nfc REQUIRED capi-network-nfc) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_NFC + ${capi-network-nfc_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_NFC + ${capi-network-nfc_LIBRARIES} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_NFC + ${CURRENT_PATH}/NFCManager.cpp + ${CURRENT_PATH}/NFCTag.cpp + ${CURRENT_PATH}/NFCTagMifareClassic.cpp + ${CURRENT_PATH}/NFCTagMifareUltra.cpp + ${CURRENT_PATH}/NdefMessage.cpp + ${CURRENT_PATH}/NdefRecord.cpp + ${CURRENT_PATH}/NFCTarget.cpp + ${CURRENT_PATH}/NFCUtil.cpp + PARENT_SCOPE +) diff --git a/src/platform/Tizen/Systeminfo/Systeminfo.cpp b/src/platform/Tizen/Systeminfo/Systeminfo.cpp new file mode 100755 index 0000000..cea6e5e --- /dev/null +++ b/src/platform/Tizen/Systeminfo/Systeminfo.cpp @@ -0,0 +1,647 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Systeminfo.h" + +using namespace TizenApis::Api::Systeminfo; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace DPL; + +namespace TizenApis { +namespace Platform { +namespace Systeminfo { + +namespace { + +void systemInfoValueCallback(keynode_t *node, void *event_ptr) +{ + if(event_ptr) { + ((EventWatchSysteminfo*)event_ptr)->getWatchValue(); + } +} + +void systemInfoNetworkCallback(keynode_t *node, void *event_ptr) +{ + if(event_ptr) { + ((Systeminfo*)event_ptr)->getWatchValue(); + } +} + +} + +#define STORAGE_INTERNAL_PATH "/opt/media" +#define STORAGE_SDCARD_PATH "/opt/storage/sdcard" +#define STORAGE_USBHOST_PATH "/opt/storage/usb" +#define MODEL_VERSION_LENGTH 5 + +enum { + STORAGE_TYPE_UNKNOWN = 0, + STORAGE_TYPE_INTERNAL = 1, + STORAGE_TYPE_MMC = 2, + STORAGE_TYPE_USBHOST = 3 +}; + +Systeminfo::OptionalProperty Systeminfo::m_Property; + +Systeminfo::Systeminfo() : m_networkRegist(REGIST_NOT) +{ + EventMgrPtr eventMgrPtr(new EventMgr()); + m_EventMgrPtr = eventMgrPtr; + if (m_Property.IsNull()) { + mapProperties properties; + properties["Power"] = BasePropertyPtr(new Power()); + m_Property = properties; + (*m_Property)["Cpu"] = BasePropertyPtr(new Cpu()); + (*m_Property)["Storage"] = BasePropertyPtr(new Storage()); + (*m_Property)["Display"] = BasePropertyPtr(new Display()); + (*m_Property)["Device"] = BasePropertyPtr(new Device()); + (*m_Property)["WifiNetwork"] = BasePropertyPtr(new WifiNetwork()); + (*m_Property)["CellularNetwork"] = BasePropertyPtr(new CellularNetwork()); + } +} + +Systeminfo::~Systeminfo() +{ + m_EventMgrPtr->clearAllEvent(); +} + +bool Systeminfo::isPropertyValid(JSContextRef context, JSValueRef property) +{ + Converter converter(context); + + std::string l_property = converter.toString(property); + mapProperties::iterator it = (*m_Property).find(l_property); + if (it == (*m_Property).end()) { + LogError("not existing property"); + return false; + } + + return true; +} + +void Systeminfo::get(const EventGetSysteminfoPtr& event) +{ + EventRequestReceiver::PostRequest(event); +} + +void Systeminfo::watch(const EventWatchSysteminfoPtr& event) +{ + if(event->getWatchType() == WATCH_TPYE_UNKNOWN) { + LogDebug("watch method is not supported"); + return; + } + // we don't support multi watch, check duplication + + event->setSysteminfoPtr(this); + m_EventMgrPtr->addEvent(event); + + EventRequestReceiver::PostRequest(event); +} + +void Systeminfo::clearWatch(const int id) +{ + switch(m_EventMgrPtr->getWatchType(id)) { + case WATCH_TPYE_POWER: + vconf_ignore_key_changed(VCONFKEY_SYSMAN_BATTERY_CAPACITY, systemInfoValueCallback); + vconf_ignore_key_changed(VCONFKEY_SYSMAN_BATTERY_CHARGE_NOW, systemInfoValueCallback); + break; + case WATCH_TYPE_DISPLAY: + vconf_ignore_key_changed(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, systemInfoValueCallback); + break; + case WATCH_TPYE_WIFINETWORK: + vconf_ignore_key_changed(VCONFKEY_WIFI_STRENGTH, systemInfoValueCallback); + if (m_networkRegist == REGIST_WIFI) { + vconf_ignore_key_changed(VCONFKEY_NETWORK_CONFIGURATION_CHANGE_IND, systemInfoNetworkCallback); + m_networkRegist = REGIST_NOT; + } else if (m_networkRegist== REGIST_ALL) { + m_networkRegist = REGIST_CELLULAR; + } + break; + case WATCH_TPYE_CELLULARNETWORK: + vconf_ignore_key_changed(VCONFKEY_TELEPHONY_PLMN, systemInfoValueCallback); + vconf_ignore_key_changed(VCONFKEY_TELEPHONY_LAC, systemInfoValueCallback); + vconf_ignore_key_changed(VCONFKEY_TELEPHONY_CELLID, systemInfoValueCallback); + vconf_ignore_key_changed(VCONFKEY_SETAPPL_STATE_DATA_ROAMING_BOOL, systemInfoValueCallback); + if (m_networkRegist == REGIST_CELLULAR) { + vconf_ignore_key_changed(VCONFKEY_NETWORK_CONFIGURATION_CHANGE_IND, systemInfoNetworkCallback); + m_networkRegist = REGIST_NOT; + } else if (m_networkRegist== REGIST_ALL) { + m_networkRegist = REGIST_WIFI; + } + break; + } + + m_EventMgrPtr->removeEvent(id); +} + +BasePropertyPtr Systeminfo::getBasePropertyPtr(JSContextRef context, JSValueRef property) +{ + Converter converter(context); + std::string l_property = converter.toString(property); + mapProperties::iterator it = (*m_Property).find(l_property); + if (it == (*m_Property).end()) { + LogError("not existing property"); + Throw(InvalidArgumentException); + return BasePropertyPtr(NULL); + } + + return it->second; +} + +bool Systeminfo::isDuplicateWatch(const char * property) +{ + EventList eventList = m_EventMgrPtr->getEventList(); + int cnt = 0; + for (EventList::iterator it = eventList.begin(); it != eventList.end(); it++) { + LogDebug("event idx=" << cnt++ << ", property=" << (*it)->getProperty()); + if (strcmp(property, (*it)->getProperty()) == 0) { + LogDebug("property is duplicated"); + return true; + } + } + return false; +} + +void Systeminfo::getWatchValue() +{ + EventList eventList = m_EventMgrPtr->getEventList(); + + if (m_networkRegist == REGIST_WIFI) { + for (EventList::iterator it = eventList.begin(); it != eventList.end(); it++) { + if (WATCH_TPYE_WIFINETWORK == (*it)->getWatchType()) { + (*it)->getWatchValue(); + break; + } + } + } else if (m_networkRegist == REGIST_CELLULAR) { + for (EventList::iterator it = eventList.begin(); it != eventList.end(); it++) { + if (WATCH_TPYE_CELLULARNETWORK == (*it)->getWatchType()) { + (*it)->getWatchValue(); + break; + } + } + } else if (m_networkRegist == REGIST_ALL) { + for (EventList::iterator it = eventList.begin(); it != eventList.end(); it++) { + if (WATCH_TPYE_WIFINETWORK == (*it)->getWatchType()) { + (*it)->getWatchValue(); + } else if (WATCH_TPYE_CELLULARNETWORK == (*it)->getWatchType()) { + (*it)->getWatchValue(); + } + } + } +} + +void Systeminfo::OnRequestReceived(const EventGetSysteminfoPtr& event) +{ + event->processGetValue(); +} + +void Systeminfo::OnRequestReceived(const EventWatchSysteminfoPtr& event) +{ + WatchOption watchOption = event->getWatchOption(); + + event->switchToManualAnswer(); + event->setCancelAllowed(true); + + switch(event->getWatchType()) { + case WATCH_TPYE_POWER: + vconf_notify_key_changed(VCONFKEY_SYSMAN_BATTERY_CAPACITY, systemInfoValueCallback, event.Get()); + vconf_notify_key_changed(VCONFKEY_SYSMAN_BATTERY_CHARGE_NOW, systemInfoValueCallback, event.Get()); + break; + case WATCH_TYPE_DISPLAY: + vconf_notify_key_changed(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, systemInfoValueCallback, event.Get()); + break; + case WATCH_TPYE_WIFINETWORK: + vconf_notify_key_changed(VCONFKEY_WIFI_STRENGTH, systemInfoValueCallback, event.Get()); + if (m_networkRegist == REGIST_NOT) { + vconf_notify_key_changed(VCONFKEY_NETWORK_CONFIGURATION_CHANGE_IND, systemInfoNetworkCallback, (void *)this); + m_networkRegist = REGIST_WIFI; + } else if (m_networkRegist== REGIST_CELLULAR) { + m_networkRegist = REGIST_ALL; + } + break; + case WATCH_TPYE_CELLULARNETWORK: + vconf_notify_key_changed(VCONFKEY_TELEPHONY_PLMN, systemInfoValueCallback, event.Get()); + vconf_notify_key_changed(VCONFKEY_TELEPHONY_LAC, systemInfoValueCallback, event.Get()); + vconf_notify_key_changed(VCONFKEY_TELEPHONY_CELLID, systemInfoValueCallback, event.Get()); + vconf_notify_key_changed(VCONFKEY_SETAPPL_STATE_DATA_ROAMING_BOOL, systemInfoValueCallback, event.Get()); + if (m_networkRegist == REGIST_NOT) { + vconf_notify_key_changed(VCONFKEY_NETWORK_CONFIGURATION_CHANGE_IND, systemInfoNetworkCallback, (void *)this); + m_networkRegist = REGIST_CELLULAR; + } else if (m_networkRegist== REGIST_WIFI) { + m_networkRegist = REGIST_ALL; + } + break; + } + event->processGetValue(); + event->setTimer(); +} + +//////////////////////////////////////////////////////////////////////////////////////// + +Systeminfo::EventMgr::EventMgr() +{ +} + +Systeminfo::EventMgr::~EventMgr() +{ +} + +void Systeminfo::EventMgr::clearAllEvent() +{ + DPL::Mutex::ScopedLock lock(&m_synchro); + + LogDebug("removing all registered events, unRemoved event=" << m_eventList.size()); + while (!m_eventList.empty()) { + EventWatchSysteminfoPtr event = m_eventList.front(); + LogDebug("removing EventId=" << event->getId()); + event->clearWatch(); + m_eventList.pop_front(); + } +} + +void Systeminfo::EventMgr::addEvent(const EventWatchSysteminfoPtr& arg) +{ + DPL::Mutex::ScopedLock lock(&m_synchro); + + m_eventList.push_back(arg); + LogDebug("Event list size=" << m_eventList.size()); +} + +void Systeminfo::EventMgr::removeEvent(WatchId id) +{ + DPL::Mutex::ScopedLock lock(&m_synchro); + LogDebug("Event id : " << id); + + EventWatchSysteminfoPtr event(NULL); + + LogDebug("trying to delete event, id=" << id); + + for (EventList::iterator it = m_eventList.begin(); it != m_eventList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + if (!event) { + LogError("event id not in the list, nothing to do"); + return; + } + + LogDebug("event list size=" << m_eventList.size()); + m_eventList.remove(event); + LogDebug( "event removed, event list size=" << m_eventList.size()); + +} + +const int Systeminfo::EventMgr::getWatchType(const int id) +{ + DPL::Mutex::ScopedLock lock(&m_synchro); + + EventWatchSysteminfoPtr event(NULL); + + for (EventList::iterator it = m_eventList.begin(); it != m_eventList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + if (!event) { + LogError("event id not in the list, nothing to do"); + return WATCH_TPYE_UNKNOWN; + } + + return event->getWatchType(); +} + +EventList Systeminfo::EventMgr::getEventList() +{ + return m_eventList; +} + +//////////////////////////////////////////////////////////////////////////////////////// + +PROPERTY_GET_SYSTEMINFO_DEFINITION(Power) { + PowerProperties powerPtr; + + int value=0; + int value2=0; + + if (vconf_get_int(VCONFKEY_SYSMAN_BATTERY_CAPACITY, &value) != 0) { + return JSValueMakeNull(context); + } else { + powerPtr.level = (double)(value)/100; + } + + if (vconf_get_int(VCONFKEY_SYSMAN_BATTERY_CHARGE_NOW, &value2) != 0) { + return JSValueMakeNull(context); + } else { + powerPtr.isCharging = (value2 == 0) ? false : true; + } + + return Tizen1_0::JSPowerInfo::createJSObject(context, powerPtr); +} + +PROPERTY_GET_SYSTEMINFO_DEFINITION(Cpu) { + Converter converter(context); + + CpuProperties cpuPtr; + FILE *pipe; + char line[LINE_MAX] = {0}; + int a, b; + bool matched = false; + + pipe = popen("top -b -n1", "r"); + + if(pipe == NULL) { + LogDebug("file open is failed "); + return JSValueMakeNull(context); + } + + pcrecpp::RE re("(\\d+).(\\d+)%id"); + + while (fgets(line, LINE_MAX-1, pipe)) { + if (re.PartialMatch(line, &a, &b)) { + matched = true; + break; + } + } + + pclose(pipe); + + if (matched) { + if(b>5) { + cpuPtr.load = (double)(a+1)/100; + } else { + cpuPtr.load = (double)(a)/100; + } + return Tizen1_0::JSCpuInfo::createJSObject(context, cpuPtr); + } else { + return JSValueMakeNull(context); + } +} + +PROPERTY_GET_SYSTEMINFO_DEFINITION(Storage) { + Converter converter(context); + + int sdcardState=0; + int usbhostState=0; + int storageCnt=0; + struct statfs fs; + StorageProperties units[3]; + + if (statfs(STORAGE_INTERNAL_PATH, &fs) < 0) { + return JSValueMakeNull(context); + } + + units[storageCnt].type = "INTERNAL"; + units[storageCnt].capacity = (unsigned long)(fs.f_bsize * fs.f_blocks); + units[storageCnt].availableCapacity = (unsigned long)(fs.f_bsize * fs.f_bavail); + units[storageCnt].isRemoveable = false; + + if(vconf_get_int(VCONFKEY_SYSMAN_MMC_STATUS, &sdcardState) == 0) { + if(sdcardState == VCONFKEY_SYSMAN_MMC_MOUNTED) { + storageCnt++; + if (statfs(STORAGE_SDCARD_PATH, &fs) < 0) { + return JSValueMakeNull(context); + } + units[storageCnt].type = "MMC"; + units[storageCnt].capacity = (unsigned long)(fs.f_bsize * fs.f_blocks); + units[storageCnt].availableCapacity = (unsigned long)(fs.f_bsize * fs.f_bavail); + units[storageCnt].isRemoveable = true; + } + } + + if(vconf_get_int(VCONFKEY_SYSMAN_USB_HOST_STATUS, &usbhostState) == 0) { + if(usbhostState == VCONFKEY_SYSMEN_USB_HOST_CONNECTED) { + storageCnt++; + if (statfs(STORAGE_USBHOST_PATH, &fs) < 0) { + return JSValueMakeNull(context); + } + units[storageCnt].type = "USBHOST"; + units[storageCnt].capacity = (unsigned long)(fs.f_bsize * fs.f_blocks); + units[storageCnt].availableCapacity = (unsigned long)(fs.f_bsize * fs.f_bavail); + units[storageCnt].isRemoveable = true; + } + } + + storageCnt++; + + std::vector storageList; + + for (int i=0; i MODEL_VERSION_LENGTH) { + result = result.substr(0, MODEL_VERSION_LENGTH); + } + device.model = "GT-" + result; + break; + } + } + file.close(); + } + + return Tizen1_0::JSDeviceInfo::createJSObject(context, device); +} + +PROPERTY_GET_SYSTEMINFO_DEFINITION(WifiNetwork) { + Converter converter(context); + WifiNetworkProperties wifiNetwork; + net_profile_info_t ProfInfo; + int status = 0; + int strength = 0; + char* ipAddr = NULL; + + if (vconf_get_int(VCONFKEY_NETWORK_STATUS, &status) == 0) { + if (status == VCONFKEY_NETWORK_WIFI) { + wifiNetwork.status = "ON"; + ipAddr = vconf_get_str(VCONFKEY_NETWORK_IP); + if(ipAddr != NULL) { + wifiNetwork.ipAddress = ipAddr; + } + memset(&ProfInfo, 0, sizeof(net_profile_info_t)); + if (net_get_active_net_info(&ProfInfo) == NET_ERR_NONE) { + if(ProfInfo.profile_type == NET_DEVICE_WIFI) { + wifiNetwork.ssid = ProfInfo.ProfileInfo.Wlan.essid; + if (vconf_get_int(VCONFKEY_WIFI_STRENGTH, &strength) != 0) { + LogDebug("vconf_get_int failed"); + } else { + wifiNetwork.signalStrength = (double)(strength/4); + } + } + } + } else { + wifiNetwork.status = "OFF"; + } + } + return Tizen1_0::JSWifiNetworkInfo::createJSObject(context, wifiNetwork); +} + +PROPERTY_GET_SYSTEMINFO_DEFINITION(CellularNetwork) { + Converter converter(context); + CellularNetworkProperties cellularNetwork; + net_profile_info_t ProfInfo; + char* ipAddr = NULL; + int cellid = 0, lac = 0; + int plmn = 0; + int isRoaming = 0; + int status = 0; + + if (vconf_get_int(VCONFKEY_NETWORK_STATUS, &status) == 0) { + if (status == VCONFKEY_NETWORK_CELLULAR) { + cellularNetwork.status = "ON"; + ipAddr = vconf_get_str(VCONFKEY_NETWORK_IP); + if(ipAddr != NULL) { + cellularNetwork.ipAddress = ipAddr; + } + memset(&ProfInfo, 0, sizeof(net_profile_info_t)); + if (net_get_active_net_info(&ProfInfo) == NET_ERR_NONE) { + if(ProfInfo.profile_type == NET_DEVICE_CELLULAR) { + cellularNetwork.apn = ProfInfo.ProfileInfo.Pdp.Apn; + + if (vconf_get_int(VCONFKEY_TELEPHONY_PLMN, &plmn) != 0) { + LogDebug("vconf_get_int failed"); + } else { + cellularNetwork.mcc = plmn / 1000; + cellularNetwork.mnc = plmn % 1000; + } + + switch(ProfInfo.ProfileInfo.Pdp.ServiceType) { + case NET_SERVICE_UNKNOWN : + cellularNetwork.serviceType = "UNKNOWN"; + break; + case NET_SERVICE_INTERNET : + cellularNetwork.serviceType = "INTERNET"; + break; + case NET_SERVICE_MMS : + cellularNetwork.serviceType = "MMS"; + break; + case NET_SERVICE_WAP : + cellularNetwork.serviceType = "WAP"; + break; + case NET_SERVICE_PREPAID_INTERNET : + cellularNetwork.serviceType = "PREPAID_INTERNET"; + break; + case NET_SERVICE_PREPAID_MMS : + cellularNetwork.serviceType = "PREPAID_MMS"; + break; + + } + LogDebug("cellularNetwork.type : " << cellularNetwork.serviceType); + + if (vconf_get_int(VCONFKEY_TELEPHONY_CELLID, &cellid) == 0) { + cellularNetwork.cellid = cellid; + } + + if (vconf_get_int(VCONFKEY_TELEPHONY_LAC, &lac) != 0) { + cellularNetwork.lac = lac; + } + + if (vconf_get_int(VCONFKEY_SETAPPL_STATE_DATA_ROAMING_BOOL, &isRoaming) != 0) { + cellularNetwork.isRoaming = (isRoaming == 0) ? false : true; + } + } + } + } else { + cellularNetwork.status = "OFF"; + } + } + return Tizen1_0::JSCellularNetworkInfo::createJSObject(context, cellularNetwork); +} + +} +} +} + diff --git a/src/platform/Tizen/Systeminfo/Systeminfo.h b/src/platform/Tizen/Systeminfo/Systeminfo.h new file mode 100755 index 0000000..46e4ba2 --- /dev/null +++ b/src/platform/Tizen/Systeminfo/Systeminfo.h @@ -0,0 +1,143 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_PLATFORM_SYSTEMINFO_H_ +#define WRTPLUGINS_PLATFORM_SYSTEMINFO_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace Systeminfo { + +enum { + WATCH_TPYE_UNKNOWN = 0, + WATCH_TPYE_POWER = 1, + WATCH_TYPE_DISPLAY = 2, + WATCH_TPYE_WIFINETWORK = 3, + WATCH_TPYE_CELLULARNETWORK = 4 +}; + +enum { + REGIST_NOT = 0, + REGIST_WIFI = 1, + REGIST_CELLULAR =2, + REGIST_ALL = 3 +}; + +typedef DPL::Atomic::ValueType WatchId; + +#define PROPERTY_DECLARATION(className, propertyName, watchType) \ + class className : public Api::Systeminfo::BaseProperty { \ + public: \ + explicit className() : Api::Systeminfo::BaseProperty() { \ + } \ + JSValueRef getValue(JSContextRef context) const; \ + const char* getProperty() const \ + { \ + return propertyName; \ + } \ + const int getWatchType() const \ + { \ + return watchType; \ + } \ + }; + +#define PROPERTY_GET_SYSTEMINFO_DEFINITION(className) JSValueRef className::getValue( \ + JSContextRef context) const + +PROPERTY_DECLARATION(Power, "Power", WATCH_TPYE_POWER) +PROPERTY_DECLARATION(Cpu, "Cpu", WATCH_TPYE_UNKNOWN) +PROPERTY_DECLARATION(Storage, "Storage", WATCH_TPYE_UNKNOWN) +PROPERTY_DECLARATION(Display, "Display", WATCH_TYPE_DISPLAY) +PROPERTY_DECLARATION(Device, "Device", WATCH_TPYE_UNKNOWN) +PROPERTY_DECLARATION(WifiNetwork, "WifiNetwork", WATCH_TPYE_WIFINETWORK) +PROPERTY_DECLARATION(CellularNetwork, "CellularNetwork", WATCH_TPYE_CELLULARNETWORK) + +typedef std::list EventList; + +class Systeminfo : public Api::Systeminfo::ISysteminfo +{ + friend class TizenApis::Api::Systeminfo::SysteminfoFactory; + friend class TizenApis::Api::Systeminfo::EventWatchSysteminfo;; + + public: + + virtual ~Systeminfo(); + virtual bool isPropertyValid(JSContextRef context, JSValueRef property); + virtual void get(const Api::Systeminfo::EventGetSysteminfoPtr& event); + virtual void watch(const Api::Systeminfo::EventWatchSysteminfoPtr& event); + virtual Api::Systeminfo::BasePropertyPtr getBasePropertyPtr(JSContextRef context, JSValueRef property); + virtual void clearWatch(const int id); + virtual bool isDuplicateWatch(const char * property); + void getWatchValue(); + + class EventMgr + { + public: + EventMgr(); + ~EventMgr(); + + void clearAllEvent(); + void addEvent(const Api::Systeminfo::EventWatchSysteminfoPtr& arg); + void removeEvent(WatchId id); + const int getWatchType(const int id); + EventList getEventList(); + + private: + EventList m_eventList; + DPL::Mutex m_synchro; + }; + typedef DPL::SharedPtr EventMgrPtr; + + protected: + Systeminfo(); + virtual void OnRequestReceived(const Api::Systeminfo::EventGetSysteminfoPtr& event); + virtual void OnRequestReceived(const Api::Systeminfo::EventWatchSysteminfoPtr& event); + + private: + typedef std::map mapProperties; + typedef DPL::Optional OptionalProperty; + + static OptionalProperty m_Property; + int m_networkRegist; + DPL::Mutex m_initializationMutex; + EventMgrPtr m_EventMgrPtr; +}; + +} +} +} + +#endif diff --git a/src/platform/Tizen/Systeminfo/config.cmake b/src/platform/Tizen/Systeminfo/config.cmake new file mode 100755 index 0000000..0a02bce --- /dev/null +++ b/src/platform/Tizen/Systeminfo/config.cmake @@ -0,0 +1,21 @@ +get_current_path() + +pkg_search_module(network REQUIRED network) +pkg_search_module(devman REQUIRED devman) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_SYSTEMINFO + ${network_INCLUDE_DIRS} + ${devman_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_SYSTEMINFO + ${network_LIBRARIES} + ${devman_LIBRARIES} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_SYSTEMINFO + ${CURRENT_PATH}/Systeminfo.cpp + PARENT_SCOPE +) diff --git a/src/platform/Tizen/TimeUtil/TZDate.cpp b/src/platform/Tizen/TimeUtil/TZDate.cpp new file mode 100755 index 0000000..134e991 --- /dev/null +++ b/src/platform/Tizen/TimeUtil/TZDate.cpp @@ -0,0 +1,602 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#include + +#include + +#include + +#include +#include +#include + +#include "TZDate.h" +#include "TimeUtilTools.h" + +using namespace TizenApis::Api::TimeUtil; +using namespace WrtDeviceApis; + +namespace TizenApis { +namespace Platform { +namespace TimeUtil { + +TZDate::TZDate(const bool isNotNull) +{ + LogDebug("entered"); + + if (isNotNull == FALSE) { + myCalendar = NULL; + } else { + UErrorCode ec = U_ZERO_ERROR; + myCalendar = Calendar::createInstance(ec); + + if (U_SUCCESS(ec)) { + TimeUtilTools Util; + Util.printDate(myCalendar); + } + else { + myCalendar = NULL; + ThrowMsg(Commons::PlatformException, "Can't make to ICU Calendar"); + } + } +} + +TZDate::TZDate(const TZDateProperties &properties) +{ + LogDebug("entered"); + + UErrorCode ec = U_ZERO_ERROR; + TimeUtilTools Util; + if (properties.timezone == "") { + myCalendar = Calendar::createInstance(ec); + if (U_SUCCESS(ec)) { + myCalendar->set(Util.toint32_t(properties.year), Util.toint32_t(properties.month), + Util.toint32_t(properties.day), Util.toint32_t(properties.hours), Util.toint32_t(properties.minutes), Util.toint32_t(properties.seconds)); + set(TZDATE_MILLISECOND, properties.milliseconds); + } else { + myCalendar = NULL; + } + } else { + myCalendar = _makeCalendar(properties); + } + + if (myCalendar != NULL) { + Util.printDate(myCalendar); + } + else { + ThrowMsg(Commons::PlatformException, "Can't make to ICU Calendar"); + } +} + +TZDate::~TZDate() +{ + LogDebug("entered"); + + if (myCalendar != NULL) + delete myCalendar; + + myCalendar = NULL; + +} + +bool TZDate::isNull() +{ + if (myCalendar == NULL) + return TRUE; + + return FALSE; +} + +Calendar *TZDate::_makeCalendar(const TZDateProperties &properties) +{ + LogDebug("entered"); + UErrorCode ec = U_ZERO_ERROR; + TimeUtilTools Util; + + Calendar *cal = Calendar::createInstance(Util.makeTimeZone(properties.timezone) ,ec); + if (U_SUCCESS(ec)) { + cal->set(Util.toint32_t(properties.year), Util.toint32_t(properties.month), + Util.toint32_t(properties.day), Util.toint32_t(properties.hours), Util.toint32_t(properties.minutes), Util.toint32_t(properties.seconds)); + cal->set(UCAL_MILLISECOND, Util.toint32_t(properties.milliseconds)); + return cal; + } + + return NULL; +} + +std::string TZDate::_getTimezoneName(Calendar *cal) +{ + UnicodeString ID; + TimeUtilTools Util; + + cal->getTimeZone().getID(ID); + std::string s_result = Util.toString(ID); + LogDebug(s_result); + return s_result; +} + +const UCalendarDateFields TZDate::_convertDateField(const TZDateFields field) +{ + switch (field) { + case TZDATE_ERA: + return UCAL_ERA; + break; + case TZDATE_YEAR: + return UCAL_YEAR; + break; + case TZDATE_MONTH: + return UCAL_MONTH; + break; + case TZDATE_WEEK_OF_YEAR: + return UCAL_WEEK_OF_YEAR; + break; + case TZDATE_WEEK_OF_MONTH: + return UCAL_WEEK_OF_MONTH; + break; + case TZDATE_DATE: + return UCAL_DATE; + break; + case TZDATE_DAY_OF_YEAR: + return UCAL_DAY_OF_YEAR; + break; + case TZDATE_DAY_OF_WEEK: + return UCAL_DAY_OF_WEEK; + break; + case TZDATE_DAY_OF_WEEK_IN_MONTH: + return UCAL_DAY_OF_WEEK_IN_MONTH; + break; + case TZDATE_AM_PM: + return UCAL_AM_PM; + break; + case TZDATE_HOUR: + return UCAL_HOUR; + break; + case TZDATE_HOUR_OF_DAY: + return UCAL_HOUR_OF_DAY; + break; + case TZDATE_MINUTE: + return UCAL_MINUTE; + break; + case TZDATE_SECOND: + return UCAL_SECOND; + break; + case TZDATE_MILLISECOND: + return UCAL_MILLISECOND; + break; + case TZDATE_ZONE_OFFSET: + return UCAL_ZONE_OFFSET; + break; + case TZDATE_DST_OFFSET: + return UCAL_DST_OFFSET; + break; + default: + return UCAL_FIELD_COUNT; + } +} + +TZDateProperties TZDate::_makeProperties(Calendar *cal) +{ + TZDateProperties result; + TimeUtilTools Util; + + result.year = _get(TZDATE_YEAR, cal); + result.month = _get(TZDATE_MONTH,cal); + result.day = _get(TZDATE_DATE, cal); + result.hours = _get(TZDATE_HOUR_OF_DAY, cal); + result.minutes = _get(TZDATE_MINUTE, cal); + result.seconds = _get(TZDATE_SECOND, cal); + result.milliseconds = _get(TZDATE_MILLISECOND, cal); + result.timezone= _getTimezoneName(cal); + + return result; +} + +std::string TZDate::getTimezone() +{ + return _getTimezoneName(myCalendar); +} + +TZDateProperties TZDate::toTimezone(const std::string timezone) { + TimeUtilTools Util; + Calendar *newCalendar = myCalendar->clone(); + newCalendar->setTimeZone(*(Util.makeTimeZone(timezone))); + + TZDateProperties newProps = _makeProperties(newCalendar); + delete newCalendar; + return newProps; +} + +long TZDate::_get(const TZDateFields field, Calendar *cal) +{ + LogDebug("<<<"); + + if (_convertDateField(field) == UCAL_FIELD_COUNT){ + LogDebug(">>> UCAL_FIELD_COUNT"); + return -1; + } + + UErrorCode ec = U_ZERO_ERROR; + TimeUtilTools Util; + int32_t value = cal->get(_convertDateField(field), ec); + if (U_SUCCESS(ec)) { + long result = Util.tolong(value); + + LogDebug(">>> result:" << result); + return result; + } + ThrowMsg(Commons::PlatformException, "Can't get Calendar value"); + return 0; +} +long TZDate::get(const TZDateFields field) +{ + LogDebug("<<<"); + + long result = _get(field, myCalendar); + if (field == TZDATE_DAY_OF_WEEK) + result--; + return result; +} + +void TZDate::set(const TZDateFields field, const long value) +{ + if (_convertDateField(field) == UCAL_FIELD_COUNT) + return; + + TimeUtilTools Util; + myCalendar->set(_convertDateField(field), Util.toint32_t(value)); + LogDebug("Field : " << field << " value : " << get(field)); +} + +long TZDate::getUTC(const TZDateFields field) +{ + if (_convertDateField(field) == UCAL_FIELD_COUNT) + return -1; + + UErrorCode ec = U_ZERO_ERROR; + TimeUtilTools Util; + + Calendar *UTCCalendar = myCalendar->clone(); + UTCCalendar->setTimeZone(*(TimeZone::getGMT())); + + int32_t value = UTCCalendar->get(_convertDateField(field), ec); + delete UTCCalendar; + + if (U_SUCCESS(ec)) { + long result = Util.tolong(value); + if (field == TZDATE_DAY_OF_WEEK) + result--; + LogDebug("result : " << result); + + return result; + } + + ThrowMsg(Commons::PlatformException, "Can't get UTC Calendar value"); + return 0; +} + +void TZDate::setUTC(const TZDateFields field, const long value) +{ + if (_convertDateField(field) == UCAL_FIELD_COUNT) + return; + + TimeUtilTools Util; + UErrorCode ec = U_ZERO_ERROR; + + long myValue = get(field); + long UTCValue = getUTC(field); + if (field == TZDATE_DAY_OF_WEEK) + UTCValue++; + set(field, myValue + value - UTCValue); + + if (!U_SUCCESS(ec)) + ThrowMsg(Commons::PlatformException, "Can't set UTC Calendar value"); +} + +long long TZDate::difference(const TZDateProperties &prop) { + LogDebug("entered"); + + TimeUtilTools Util; + UErrorCode ec = U_ZERO_ERROR; + + Calendar *otherCalendar = _makeCalendar(prop); + + UDate myTime = myCalendar->getTime(ec); + + if (U_SUCCESS(ec)) { + UDate otherTime = otherCalendar->getTime(ec); + if (U_SUCCESS(ec)) { + LogDebug("myCalendar"); + Util.printDate(myCalendar); + LogDebug("otherCalendar"); + Util.printDate(otherCalendar); + delete otherCalendar; + + LogDebug("myTime : " <(myTime - otherTime); + } + } + delete otherCalendar; + ThrowMsg(Commons::PlatformException, "Calendar error in difference"); + return 0; +} + +TZDateProperties TZDate::addDuration(const DurationProperties &duration) { + LogDebug("entered"); + UErrorCode ec = U_ZERO_ERROR; + + TimeUtilTools Util; + + Calendar *cal = myCalendar->clone(); + if (duration.unit == DAYS_UNIT) { + cal->add(UCAL_DATE, Util.toint32_t(duration.length), ec); + } else if (duration.unit == MINUTES_UNIT) { + cal->add(UCAL_MINUTE, Util.toint32_t(duration.length), ec); + } else if (duration.unit == HOURS_UNIT) { + cal->add(UCAL_HOUR_OF_DAY, Util.toint32_t(duration.length), ec); + } else if (duration.unit == MSECS_UNIT) { + cal->add(UCAL_MILLISECOND, Util.toint32_t(duration.length), ec); + } else { + cal->add(UCAL_SECOND, Util.toint32_t(duration.length), ec); + } + TZDateProperties result = _makeProperties(cal); + Util.printDate(cal); + delete cal; + + if (!U_SUCCESS(ec)) + ThrowMsg(Commons::PlatformException, "Calendar error in addDuration"); + return result; + +} + +TZDateProperties TZDate::toUTC() { + LogDebug("entered"); + TimeUtilTools Util; + TZDateProperties result; + Calendar *UTCCalendar = myCalendar->clone(); + + try { + UTCCalendar->setTimeZone(*(TimeZone::getGMT())); + result = _makeProperties(UTCCalendar); + Util.printDate(UTCCalendar); + delete UTCCalendar; + } catch (Commons::PlatformException) { + delete UTCCalendar; + ThrowMsg(Commons::PlatformException, "Calendar error in toUTC"); + } + + return result; +} + +TZDateProperties TZDate::toLocalTimezone() { + LogDebug("entered"); + TimeUtilTools Util; + TZDateProperties result; + Calendar *localCalendar = myCalendar->clone(); + + try { + localCalendar->setTimeZone(*(TimeZone::createDefault())); + result = _makeProperties(localCalendar); + Util.printDate(localCalendar); + delete localCalendar; + } catch (Commons::PlatformException) { + delete localCalendar; + ThrowMsg(Commons::PlatformException, "Calendar error in toLocalTimezone"); + } + return result; +} + +double TZDate::getTime() { + LogDebug("entered"); + UErrorCode ec = U_ZERO_ERROR; + + UDate date = myCalendar->getTime(ec); + if (U_SUCCESS(ec)) + return static_cast(date); + + ThrowMsg(Commons::PlatformException, "can't get time"); + return 0; +} + + std::string TZDate::toDateString(bool bLocale) { + UErrorCode ec = U_ZERO_ERROR; + UnicodeString str; + TimeUtilTools Util; + + DateFormat *fmt = new SimpleDateFormat(UnicodeString("EEE MMM dd yyyy"), (bLocale ? Locale::getDefault() : Locale::getEnglish()), ec); + if (U_SUCCESS(ec)) { + fmt->setCalendar(*myCalendar); + fmt->format(myCalendar->getTime(ec), str); + delete fmt; + + if (U_SUCCESS(ec)) { + std::string result = Util.toString(str); + str.remove(); + + LogDebug (result); + return result; + } + } + + ThrowMsg(Commons::PlatformException, "can't make SimpleDateFormat or can't get time"); + return ""; + } + + std::string TZDate::toTimeString(bool bLocale) { + + UErrorCode ec = U_ZERO_ERROR; + UnicodeString str; + TimeUtilTools Util; + + DateFormat *fmt = new SimpleDateFormat(UnicodeString("HH:mm:ss ZZZZ"), (bLocale ? Locale::getDefault() : Locale::getEnglish()), ec); + if (U_SUCCESS(ec)) { + fmt->setCalendar(*myCalendar); + fmt->format(myCalendar->getTime(ec), str); + delete fmt; + + if (U_SUCCESS(ec)) { + std::string result = Util.toString(str); + result.erase(result.length() - 3, 1); //GMT +XX:XX -> delete ':' + str.remove(); + + LogDebug (result); + return result; + } + } + + ThrowMsg(Commons::PlatformException, "can't make SimpleDateFormat or can't get time"); + return ""; + } + + std::string TZDate::toString(bool bLocale) { + LogDebug("entered"); + + UErrorCode ec = U_ZERO_ERROR; + UnicodeString str; + TimeUtilTools Util; + + DateFormat *fmt = new SimpleDateFormat(UnicodeString("EEE MMM dd yyyy HH:mm:ss ZZZZ"),(bLocale ? Locale::getDefault() : Locale::getEnglish()), ec); + if (U_SUCCESS(ec)) { + fmt->setCalendar(*myCalendar); + fmt->format(myCalendar->getTime(ec), str); + delete fmt; + + if (U_SUCCESS(ec)) { + std::string result = Util.toString(str); + if ((result.at(result.length() - 3) > 0) && (result.at(result.length() - 3) == ':')) + result.erase(result.length() - 3, 1); //GMT +XX:XX -> delete ':' + str.remove(); + + LogDebug (result); + + return result; + } + } + ThrowMsg(Commons::PlatformException, "can't make SimpleDateFormat or can't get time"); + return ""; +} + +std::string TZDate::getTimezoneAbbreviation() { + LogDebug("entered"); + + UErrorCode ec = U_ZERO_ERROR; + UnicodeString str; + TimeUtilTools Util; + + DateFormat *fmt = new SimpleDateFormat(UnicodeString("V"), Locale::getEnglish(), ec); + if (U_SUCCESS(ec)) { + fmt->setCalendar(*myCalendar); + fmt->format(myCalendar->getTime(ec), str); + delete fmt; + + if (U_SUCCESS(ec)) { + std::string result = Util.toString(str); + str.remove(); + + LogDebug (result); + + return result; + } + } + ThrowMsg(Commons::PlatformException, "can't make SimpleDateFormat or can't get time"); + return ""; +} + +long TZDate::secondsFromUTC() { + LogDebug("entered"); + UErrorCode ec = U_ZERO_ERROR; + TimeUtilTools Util; + + int32_t zoneOffset = myCalendar->get(UCAL_ZONE_OFFSET, ec); + if (!U_SUCCESS(ec)) { + ThrowMsg(Commons::PlatformException, "can't get zone offset"); + return 0; + } + + int32_t dstOffset = myCalendar->get(UCAL_DST_OFFSET, ec); + if (!U_SUCCESS(ec)) { + ThrowMsg(Commons::PlatformException, "can't get dst offset"); + return 0; + } + + long result = ( Util.tolong(zoneOffset + dstOffset)) / MILLISTOSEC; + + LogDebug("result : " << result); + return result; +} + +bool TZDate::isDST() { + LogDebug("entered"); + UErrorCode ec = U_ZERO_ERROR; + TimeUtilTools Util; + UBool result = myCalendar->inDaylightTime(ec); + + if (!U_SUCCESS(ec)) { + ThrowMsg(Commons::PlatformException, "can't inDaylightTime value from ICU"); + return FALSE; + } + + return static_cast(result); +} + +TZDateProperties TZDate::getDSTTransition(DSTTransition trans) { + LogDebug("entered"); + TimeUtilTools Util; + UErrorCode ec = U_ZERO_ERROR; + TZDateProperties props; + UDate DSTTransitionDate = myCalendar->getTime(ec); + + if (U_SUCCESS(ec)) { + UnicodeString *ID = Util.toUnicodeString(getTimezone()); + + VTimeZone *Vtz = VTimeZone::createVTimeZoneByID(*ID); + delete ID; + + TimeZoneTransition tzTrans; + if (Vtz->useDaylightTime() == TRUE) { + UBool result = false; + if (trans == NEXT_TRANSITION) + result = Vtz->getNextTransition(DSTTransitionDate, FALSE, tzTrans); + else + result = Vtz->getPreviousTransition(DSTTransitionDate, FALSE, tzTrans); + if (result == TRUE) { + LogDebug("result is TRUE"); + DSTTransitionDate = tzTrans.getTime(); + } + } + delete Vtz; + + Calendar *DSTTransCalendar = myCalendar->clone(); + DSTTransCalendar->setTime(DSTTransitionDate, ec); + if (U_SUCCESS(ec)) { + props = _makeProperties(DSTTransCalendar); + delete DSTTransCalendar; + return props; + } + delete DSTTransCalendar; + } + ThrowMsg(Commons::PlatformException, "can't getDSTTransition value from ICU"); + return props; +} + +} +} +} diff --git a/src/platform/Tizen/TimeUtil/TZDate.h b/src/platform/Tizen/TimeUtil/TZDate.h new file mode 100755 index 0000000..3bdee3d --- /dev/null +++ b/src/platform/Tizen/TimeUtil/TZDate.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#ifndef _TZDATE_H_ +#define _TZDATE_H_ + +#include +#include + +#include +#include + +using namespace TizenApis::Api::TimeUtil; + +namespace TizenApis { +namespace Platform { +namespace TimeUtil { + +class TZDate : public ITZDate +{ + + friend class TimeUtilFactory; + + public: + TZDate(const bool isNotNull); + TZDate(const TZDateProperties &properties); + virtual ~TZDate(); + + virtual bool isNull(); + virtual long get(const TZDateFields field); + virtual std::string getTimezone(); + virtual TZDateProperties toTimezone(const std::string timezone); + virtual void set(const TZDateFields field, const long value); + + virtual long getUTC(const TZDateFields field); + virtual void setUTC(const TZDateFields field, const long value); + + virtual long long difference(const TZDateProperties &prop); + virtual TZDateProperties addDuration(const DurationProperties &duration); + virtual TZDateProperties toUTC(); + virtual TZDateProperties toLocalTimezone(); + + virtual double getTime(); + virtual std::string toDateString(bool bLocale = false) ; + virtual std::string toTimeString(bool bLocale = false); + virtual std::string toString(bool bLocale = false); + + virtual std::string getTimezoneAbbreviation(); + virtual long secondsFromUTC(); + virtual bool isDST(); + virtual TZDateProperties getDSTTransition(DSTTransition trans); + + private: + long _get(const TZDateFields field, Calendar *cal); + std::string _getTimezoneName(Calendar *cal); + const UCalendarDateFields _convertDateField(const TZDateFields field); + + Calendar * _makeCalendar(const TZDateProperties &properties); + TZDateProperties _makeProperties(Calendar *cal); + + Calendar *myCalendar; + +}; + +} +} +} + +#endif /* _DATETIME_H_ */ diff --git a/src/platform/Tizen/TimeUtil/TimeUtil.cpp b/src/platform/Tizen/TimeUtil/TimeUtil.cpp new file mode 100755 index 0000000..d27d373 --- /dev/null +++ b/src/platform/Tizen/TimeUtil/TimeUtil.cpp @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include +#include + +#include "TimeUtil.h" +#include "TimeUtilTools.h" + +using namespace TizenApis::Api::TimeUtil; +using namespace WrtDeviceApis; + +namespace TizenApis { +namespace Platform { +namespace TimeUtil { + +TimeUtil::TimeUtil() +{ + LogDebug("entered"); +} + +TimeUtil::~TimeUtil() +{ + LogDebug("entered"); + +} + +void TimeUtil::setCurrentTZDate(const TZDateProperties &tzdate){ + ThrowMsg(Commons::UnsupportedException, "Not support to set current DateTime"); +} + +std::string TimeUtil::getLocalTimezone() { + LogDebug("entered"); + UnicodeString idResult; + UChar *result = (UChar*)malloc(sizeof(UChar)*1024); + int32_t result_capacity = 1024; + int32_t len; + UErrorCode ec = U_ZERO_ERROR; + + TimeZone* zone = TimeZone::createDefault(); + UnicodeString ID; + zone->getID(ID); + len = ID.extract(result, result_capacity, ec); + + delete zone; + + if (U_SUCCESS(ec)) { + try { + TimeUtilTools Util; + std::string s_result = Util.strtoutf8(result); + LogDebug("result : " << s_result); + + if (result) { + free(result); + result= NULL; + } + + return s_result; + } catch (Commons::PlatformException) { + LogError("can't get the local timezone's name"); + } + } + + if (result) { + free(result); + result= NULL; + } + + ThrowMsg(Commons::PlatformException, "Can't get Local Timezone"); + return ""; +} + + +std::string TimeUtil::getUTCTimezone() { + LogDebug("entered"); + UnicodeString idResult; + UChar *result = (UChar*)malloc(sizeof(UChar)*1024); + int32_t result_capacity = 1024; + int32_t len; + UErrorCode ec = U_ZERO_ERROR; + UnicodeString ID; + + const TimeZone *UTCTimezone = TimeZone::getGMT(); + UTCTimezone->getID(ID); + len = ID.extract(result, result_capacity, ec); + + if (U_SUCCESS(ec)) { + try { + TimeUtilTools Util; + std::string s_result = Util.strtoutf8(result); + if (result) { + free(result); + result= NULL; + } + + LogDebug("result : " << s_result); + + return s_result; + } catch(Commons::PlatformException) { + LogError("can't get the UTC timezone's name"); + } + } + if (result) { + free(result); + result= NULL; + } + ThrowMsg(Commons::PlatformException, "Can't get UTC Timezone"); + return ""; +} + +std::vector TimeUtil::getAvailableTimezones(){ + UErrorCode ec = U_ZERO_ERROR; + StringEnumeration * tzen = TimeZone::createEnumeration(); + const char *str = NULL; + int32_t count = tzen->count(ec); + std::vector timezones; + + LogDebug("count: " << count); + + if (U_SUCCESS(ec)) { + int i = 0; + + do { + int32_t resultLen = 0; + + str = tzen->next(&resultLen, ec); + if(U_SUCCESS(ec)) { + std::string timezone = str; + timezones.push_back(timezone); + i++; + } + }while((str!=NULL) && (i < count)); + } else { + ThrowMsg(Commons::PlatformException, "Can't get timezones list"); + } + return timezones;; +} + +std::string TimeUtil::getDateFormat(const bool b_shortFormat) { + LogDebug("entered"); + + if (b_shortFormat) + return "d/m/y"; + else + return "D, M d y"; +} + +std::string TimeUtil::getTimeFormat(){ + LogDebug("entered"); + + return "h:m:s ap"; + +} + +} +} +} diff --git a/src/platform/Tizen/TimeUtil/TimeUtil.h b/src/platform/Tizen/TimeUtil/TimeUtil.h new file mode 100755 index 0000000..c92fce8 --- /dev/null +++ b/src/platform/Tizen/TimeUtil/TimeUtil.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#ifndef _TIMEUTIL_H_ +#define _TIMEUTIL_H_ + +#include +#include +#include +#include +#include + +using namespace TizenApis::Api::TimeUtil; + +namespace TizenApis { +namespace Platform { +namespace TimeUtil { + +class TimeUtil : public ITimeUtil +{ + friend class TimeUtilFactory; + + public: + TimeUtil(); + virtual ~TimeUtil(); + virtual void setCurrentTZDate(const TZDateProperties &tzdate); + virtual std::string getLocalTimezone(); + virtual std::string getUTCTimezone(); + virtual std::vector getAvailableTimezones(); + virtual std::string getDateFormat(const bool b_shortFormat); + virtual std::string getTimeFormat(); +}; + +} +} +} + +#endif /* _TIMEUTIL_H_ */ diff --git a/src/platform/Tizen/TimeUtil/TimeUtilTools.cpp b/src/platform/Tizen/TimeUtil/TimeUtilTools.cpp new file mode 100755 index 0000000..093fcdb --- /dev/null +++ b/src/platform/Tizen/TimeUtil/TimeUtilTools.cpp @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#include +#include +#include + +#include + +#include "TimeUtilTools.h" +#include + +namespace TizenApis { +namespace Platform { +namespace TimeUtil { + +using namespace WrtDeviceApis; + +UChar* TimeUtilTools::uastrcpy(const char *chars) +{ + int len; + UChar *str; + len = strlen(chars); + str = (UChar *) malloc(sizeof(UChar) *(len + 1)); + if (!str) + return NULL; + u_uastrcpy(str, chars); + return str; +} + +char* TimeUtilTools::strtoutf8(const UChar* unichars) +{ + int len; + int lenstr; + int lenutf8; + char *str; + UErrorCode status = U_ZERO_ERROR; + + len = u_strlen(unichars); + lenstr = sizeof(char) * 4 * (len + 1); + str = (char*)malloc(lenstr); + if (!str) return NULL; + u_strToUTF8(str, lenstr, &lenutf8, unichars, len, &status); + + if (U_SUCCESS(status)) + return str; + + if (str) + free (str); + + ThrowMsg(Commons::PlatformException, "Converting error"); + return NULL; +} + +long TimeUtilTools::tolong(const int32_t num) +{ + return static_cast(num); +} + +int32_t TimeUtilTools::toint32_t(const long long num) +{ + return static_cast(num); +} + +int32_t TimeUtilTools::toint32_t(const long num) +{ + return static_cast(num); +} + +int32_t TimeUtilTools::toint32_t(const int num) +{ + return static_cast(num); +} + +UnicodeString *TimeUtilTools::toUnicodeString(const std::string str) +{ + UChar *chr = uastrcpy(str.c_str()); + UnicodeString *ID = new UnicodeString(chr); + + delete chr; + return ID; +} + +std::string TimeUtilTools::toString(UnicodeString uniStr) +{ + UChar *result = (UChar*)malloc(sizeof(UChar)*1024); + int32_t result_capacity = 1024; + UErrorCode ec = U_ZERO_ERROR; + + uniStr.extract(result, result_capacity, ec); + + if (U_SUCCESS(ec)) { + try { + std::string str = strtoutf8(result); + + if (result) { + free(result); + } + + return str; + } catch(Commons::PlatformException) { + LogError("converting error"); + } + } + + if (result) { + free(result); + } + ThrowMsg(Commons::PlatformException, "Converting error"); + return ""; +} + +TimeZone *TimeUtilTools::makeTimeZone(const std::string &name) +{ + LogDebug("entered timezone name : " << name); + + UnicodeString *ID = toUnicodeString(name); + + TimeZone *tz = TimeZone::createTimeZone(*ID); + delete ID; + + return tz; +} + + +void TimeUtilTools::printDate(Calendar *cal) +{ + UErrorCode ec = U_ZERO_ERROR; + TimeUtilTools Util; + + if (cal == NULL) + return; + + LogDebug("year : " << Util.tolong(cal->get(UCAL_YEAR, ec))); + LogDebug("month : " << Util.tolong(cal->get(UCAL_MONTH, ec))); + LogDebug("day : " << Util.tolong(cal->get(UCAL_DATE, ec))); + LogDebug("hours : " << Util.tolong(cal->get(UCAL_HOUR, ec))); + LogDebug("hours of day : " << Util.tolong(cal->get(UCAL_HOUR_OF_DAY, ec))); + LogDebug("AM/PM : " << Util.tolong(cal->get(UCAL_AM_PM, ec))); + LogDebug("dayofweek : " << Util.tolong(cal->get(UCAL_DAY_OF_WEEK, ec))); + LogDebug("minues : " << Util.tolong(cal->get(UCAL_MINUTE, ec))); + LogDebug("seconds : " << Util.tolong(cal->get(UCAL_SECOND, ec))); + LogDebug("miliseconds : " << Util.tolong(cal->get(UCAL_MILLISECOND, ec))); + LogDebug("zone offset : " << Util.tolong(cal->get(UCAL_ZONE_OFFSET, ec))); + LogDebug("dst offset : " << Util.tolong(cal->get(UCAL_DST_OFFSET, ec))); + LogDebug("is leap month? : " << Util.tolong(cal->get(UCAL_IS_LEAP_MONTH, ec))); +} + +} +} +} diff --git a/src/platform/Tizen/TimeUtil/TimeUtilTools.h b/src/platform/Tizen/TimeUtil/TimeUtilTools.h new file mode 100755 index 0000000..9142dae --- /dev/null +++ b/src/platform/Tizen/TimeUtil/TimeUtilTools.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#ifndef _TIMEUTILTOOLS_H_ +#define _TIMEUTILTOOLS_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Platform { +namespace TimeUtil { + +#define MILLISTOSEC 1000 + +class TimeUtilTools +{ + + public: + TimeUtilTools() {} + virtual ~TimeUtilTools() {} + UChar* uastrcpy(const char *chars); + char* strtoutf8(const UChar* unichars); + long tolong(const int32_t num); + int32_t toint32_t(const long long num); + int32_t toint32_t(const long num); + int32_t toint32_t(const int num); + UnicodeString *toUnicodeString(const std::string str); + std::string toString(UnicodeString uniStr); + TimeZone *makeTimeZone(const std::string &name); + void printDate(Calendar *cal); + +}; + +} +} +} + +#endif /* _TIMEUTILTOOLS_H_ */ diff --git a/src/platform/Tizen/TimeUtil/config.cmake b/src/platform/Tizen/TimeUtil/config.cmake new file mode 100755 index 0000000..12338da --- /dev/null +++ b/src/platform/Tizen/TimeUtil/config.cmake @@ -0,0 +1,19 @@ +get_current_path() + +pkg_search_module(pkgs_time REQUIRED icu-i18n icu-io icu-le icu-lx icu-uc) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_TIMEUTIL + ${pkgs_time_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_TIMEUTIL + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_TIMEUTIL + ${CURRENT_PATH}/TimeUtil.cpp + ${CURRENT_PATH}/TZDate.cpp + ${CURRENT_PATH}/TimeUtilTools.cpp + PARENT_SCOPE +) diff --git a/src/platform/Tizen/config.cmake b/src/platform/Tizen/config.cmake new file mode 100755 index 0000000..a56580b --- /dev/null +++ b/src/platform/Tizen/config.cmake @@ -0,0 +1,17 @@ +include_config_file(DBus) +include_config_file(Calendar) +include_config_file(Contact) +include_config_file(Geocoder) +include_config_file(Call) +include_config_file(Bluetooth) +include_config_file(Application) +include_config_file(Messaging) +include_config_file(TimeUtil) +include_config_file(Systeminfo) +include_config_file(NFC) + +#include_config_file(Account) +#include_config_file(Accelerometer) +#include_config_file(Orientation) +#include_config_file(Gyroscope) +#include_config_file(Filesystem) diff --git a/src/standards/CMakeLists.txt b/src/standards/CMakeLists.txt new file mode 100644 index 0000000..b204dff --- /dev/null +++ b/src/standards/CMakeLists.txt @@ -0,0 +1,6 @@ +set(STANDARD_FILE_DESTINATION /usr/lib/wrt-plugins) + +add_subdirectory(Tizen) +#add_subdirectory(W3C) + +#INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/standard-features-list DESTINATION ${STANDARD_FILE_DESTINATION}) diff --git a/src/standards/Tizen/Application/ApplicationAnswerReceiver.cpp b/src/standards/Tizen/Application/ApplicationAnswerReceiver.cpp new file mode 100755 index 0000000..5c1b7c4 --- /dev/null +++ b/src/standards/Tizen/Application/ApplicationAnswerReceiver.cpp @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "JSApplicationInformation.h" +#include "ApplicationAnswerReceiver.h" +#include "ApplicationConverter.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +using namespace std; +using namespace TizenApis::Api::Application; +using namespace WrtDeviceApis; +using namespace TizenApis::Commons; + +ApplicationAnswerReceiver::ApplicationAnswerReceiver(const CommonsJavaScript::JSCallbackManagerPtr &callbackManager) : + EventAnswerReceiver (WrtDeviceApis::Commons::ThreadEnum::NULL_THREAD), + EventAnswerReceiver (WrtDeviceApis::Commons::ThreadEnum::NULL_THREAD), + EventAnswerReceiver (WrtDeviceApis::Commons::ThreadEnum::NULL_THREAD), + m_callbackManager(callbackManager) { +} + +ApplicationAnswerReceiver::ApplicationAnswerReceiver(const LaunchServicePrivateDataPtr &launchServiceCallbackManager) : + EventAnswerReceiver (WrtDeviceApis::Commons::ThreadEnum::NULL_THREAD), + EventAnswerReceiver (WrtDeviceApis::Commons::ThreadEnum::NULL_THREAD), + EventAnswerReceiver (WrtDeviceApis::Commons::ThreadEnum::NULL_THREAD), + m_privateData(launchServiceCallbackManager) { + LogDebug("<<<"); +} + +ApplicationAnswerReceiver::~ApplicationAnswerReceiver() { +} + +void ApplicationAnswerReceiver::OnAnswerReceived(const EventListInstalledApplicationsPtr &event) +{ + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + Try + { + ApplicationInformationArrayPtr appinfoArray = event->getApplicationInformationArray(); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(m_callbackManager->getContext()); + JSValueRef result = converter->toJSValueRef(appinfoArray); + + m_callbackManager->callOnSuccess(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error during function executing"); + JSContextRef context = m_callbackManager->getContext(); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::UNKNOWN_ERROR,"unknown error"); + m_callbackManager->callOnError(errorObject); + } + } + else { + LogDebug("Operation failed. Exception code: " << event->getExceptionCode()); + JSContextRef context = m_callbackManager->getContext(); + JSValueRef errorObject = NULL; + + WrtDeviceApis::Commons::ExceptionCodes::Enumeration exception = event->getExceptionCode(); + switch(exception){ + case WrtDeviceApis::Commons::ExceptionCodes::NotFoundException: + errorObject = JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::NOT_FOUND_ERROR,"given package is not found"); + break; + case WrtDeviceApis::Commons::ExceptionCodes::PlatformException: + errorObject = JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::UNKNOWN_ERROR,"platform exception"); + break; + default: + errorObject = JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::UNKNOWN_ERROR,"unknown error"); + break; + } + m_callbackManager->callOnError(errorObject); + } +} + +void ApplicationAnswerReceiver::OnAnswerReceived(const EventGetApplicationPtr &event) +{ + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + Try + { + ApplicationInformationPtr appinfo = event->getApplicationInformation(); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(m_callbackManager->getContext()); + JSValueRef result = converter->toJSValueRef(appinfo); + + m_callbackManager->callOnSuccess(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error during getApplication() executing"); + JSContextRef context = m_callbackManager->getContext(); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::UNKNOWN_ERROR,"unknown error"); + m_callbackManager->callOnError(errorObject); + } + } + else { + LogDebug("Operation failed. Exception code: " << event->getExceptionCode()); + JSContextRef context = m_callbackManager->getContext(); + JSValueRef errorObject = NULL; + + WrtDeviceApis::Commons::ExceptionCodes::Enumeration exception = event->getExceptionCode(); + switch(exception){ + case WrtDeviceApis::Commons::ExceptionCodes::NotFoundException: + errorObject = JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::NOT_FOUND_ERROR,"given package is not found"); + break; + case WrtDeviceApis::Commons::ExceptionCodes::PlatformException: + errorObject = JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::UNKNOWN_ERROR,"platform exception"); + break; + default: + errorObject = JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::UNKNOWN_ERROR,"unknown error"); + break; + } + m_callbackManager->callOnError(errorObject); + } + LogDebug(">>>"); +} + +void ApplicationAnswerReceiver::OnAnswerReceived(const EventLaunchServicePtr &event) +{ + LogDebug("<<<"); + LaunchServicePrivateDataPtr privateData = + DPL::StaticPointerCast(event->getPrivateData()); + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + LogDebug("OnAnswerReceived"); + Try + { + if( event->getCallbackType() == EventLaunchService::APPLICATION_SERVICE_CALLBACK) + { + CommonsJavaScript::JSCallbackManagerPtr callbackManager = privateData->getCallbackManager(); + callbackManager->callOnSuccess(); + + LogDebug("after callOnSuccess"); + + } + else if(event->getCallbackType() == EventLaunchService::APPLICATION_SERVICE_REPLY_SUCCESS_CALLBACK) + { + + CommonsJavaScript::JSCallbackManagerPtr replyCallbackManager = privateData->getReplyCallbackManager(); + if(replyCallbackManager) + { + LogDebug("check ApplicationServiceReply"); + ApplicationServiceReplyPtr reply = event->getServiceReply(); + + ApplicationConverterFactory::ConverterType converter = + ApplicationConverterFactory::getConverter(replyCallbackManager->getContext()); + JSValueRef jsObj = converter->toJSValueRef(reply); + + replyCallbackManager->callOnSuccess(jsObj); + LogDebug("after replyCallbackManager onsuccess"); + } + } + else if(event->getCallbackType() == EventLaunchService::APPLICATION_SERVICE_REPLY_FAIL_CALLBACK) + { + + CommonsJavaScript::JSCallbackManagerPtr replyCallbackManager = privateData->getReplyCallbackManager(); + if(replyCallbackManager) + { + + LogDebug("check ApplicationServiceReply"); + ApplicationServiceReplyPtr reply = event->getServiceReply(); + + ApplicationConverterFactory::ConverterType converter = + ApplicationConverterFactory::getConverter(replyCallbackManager->getContext()); + JSValueRef jsObj = converter->toJSValueRef(reply); + + replyCallbackManager->callOnError(jsObj); + LogDebug("after replyCallbackManager onfail"); + } + } + else if(event->getCallbackType() == EventLaunchService::APPLICATION_SERVICE_REPLY_CANCEL_CALLBACK) + { + CommonsJavaScript::JSCallbackManagerPtr replyCancelCallbackManager = privateData->getReplyCancelCallbackManager(); + if(replyCancelCallbackManager) + { + LogDebug("replyCancelCallbackManager"); + replyCancelCallbackManager->callOnSuccess(); + LogDebug("after replyCallback oncancel"); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error during function executing"); + } + } + else { + LogDebug("Operation failed. Exception code: " << event->getExceptionCode()); + + JSValueRef errorObject = NULL; + CommonsJavaScript::JSCallbackManagerPtr callbackManager = privateData->getCallbackManager(); + if(callbackManager == NULL ) + { + LogWarning("callbackManager is null"); + } + JSContextRef context = callbackManager->getContext(); + + WrtDeviceApis::Commons::ExceptionCodes::Enumeration exception = event->getExceptionCode(); + switch(exception){ + case WrtDeviceApis::Commons::ExceptionCodes::NotFoundException: + errorObject = JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::NOT_FOUND_ERROR,"given package is not found"); + break; + case WrtDeviceApis::Commons::ExceptionCodes::PlatformException: + errorObject = JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::UNKNOWN_ERROR,"platform exception"); + break; + default: + errorObject = JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::UNKNOWN_ERROR,"unknown error"); + break; + } + callbackManager->callOnError(errorObject); + } + LogDebug(">>>"); +} + +} +} +} diff --git a/src/standards/Tizen/Application/ApplicationAnswerReceiver.h b/src/standards/Tizen/Application/ApplicationAnswerReceiver.h new file mode 100755 index 0000000..fdceee1 --- /dev/null +++ b/src/standards/Tizen/Application/ApplicationAnswerReceiver.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_TIZEN_APPLICATION_ANSWER_RECEIVER_H_ +#define TIZENAPIS_TIZEN_APPLICATION_ANSWER_RECEIVER_H_ + +#include +#include + +#include +#include +#include +#include +#include "LaunchServicePrivateData.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +using namespace WrtDeviceApis::CommonsJavaScript; + +class ApplicationAnswerReceiver : + public WrtDeviceApis::Commons::EventAnswerReceiver< Api::Application::EventListInstalledApplications>, + public WrtDeviceApis::Commons::EventAnswerReceiver< Api::Application::EventGetApplication>, + public WrtDeviceApis::Commons::EventAnswerReceiver< Api::Application::EventLaunchService> +{ + public: + explicit ApplicationAnswerReceiver(const JSCallbackManagerPtr &callbackManager); + explicit ApplicationAnswerReceiver(const LaunchServicePrivateDataPtr &ApplicatoinServiceCallback); + virtual ~ApplicationAnswerReceiver(); + + protected: + void OnAnswerReceived(const Api::Application::EventListInstalledApplicationsPtr &event); + void OnAnswerReceived(const Api::Application::EventGetApplicationPtr &event); + void OnAnswerReceived(const Api::Application::EventLaunchServicePtr &event); + + private: + JSCallbackManagerPtr m_callbackManager; + LaunchServicePrivateDataPtr m_privateData; +}; + +} +} +} +#endif diff --git a/src/standards/Tizen/Application/ApplicationConverter.cpp b/src/standards/Tizen/Application/ApplicationConverter.cpp new file mode 100755 index 0000000..477394d --- /dev/null +++ b/src/standards/Tizen/Application/ApplicationConverter.cpp @@ -0,0 +1,353 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include + +#include "ApplicationConverter.h" +#include "JSApplicationInformation.h" +#include "JSApplicationInformationArray.h" +#include "JSApplicationServiceExtraDataArray.h" +#include "JSApplicationServiceExtraData.h" +#include "JSApplicationServiceRequest.h" +#include "JSApplicationServiceReply.h" + +namespace { + const char* APPLICATOIN_ATTRIBUTE_NAME = "name"; + const char* APPLICATOIN_ATTRIBUTE_PACKAGE_NAME = "packageName"; + const char* APPLICATOIN_ATTRIBUTE_ICONF_PATH = "iconPath"; + const char* APPLICATOIN_ATTRIBUTE_VERSION = "version"; + const char* APPLICATOIN_ATTRIBUTE_EXTRA_KEY = "key"; + const char* APPLICATOIN_ATTRIBUTE_EXTRA_VALUE = "value"; + const char* APPLICATOIN_ATTRIBUTE_OPERATION = "operation"; + const char* APPLICATOIN_ATTRIBUTE_URI = "uri"; + const char* APPLICATOIN_ATTRIBUTE_MIME = "mime"; + const char* APPLICATOIN_ATTRIBUTE_EXTRADATA = "extraData"; +} + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace Api::Application; + +std::vector ApplicationConverter::m_allowedApplicationInformation; +std::vector ApplicationConverter::m_allowedApplicationServiceRequest; +std::vector ApplicationConverter::m_allowedApplicationServiceReply; +std::vector ApplicationConverter::m_allowedApplicationServiceExtraData; + +ApplicationConverter::ApplicationConverter(JSContextRef context) : Converter(context) +{ + static bool init = initializeAllowedProperties(); + (void) init; +} + +ApplicationConverter::~ApplicationConverter() +{ +} + +JSValueRef ApplicationConverter::toJSValueRef(const ApplicationInformationPtr &arg) +{ + if(arg == NULL) + { + Throw(Commons::InvalidArgumentException); + } + return CommonsJavaScript::JSUtils::makeObject(m_context, JSApplicationInformation::getClassRef(), arg); +} + +ApplicationInformationPtr ApplicationConverter::toApplicationInformation(const JSValueRef &jsValue) +{ + if(JSApplicationInformation::isObjectOfClass(m_context, jsValue)) + return JSApplicationInformation::getApplicationInformation(m_context, jsValue); + + CommonsJavaScript::Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedApplicationInformation, jsValue)) { + LogError("invalid properties in contact object"); + ThrowMsg(Commons::ConversionException, "Wrong attribute"); + } + + const ScopedJSStringRef nameStr(JSStringCreateWithUTF8CString(APPLICATOIN_ATTRIBUTE_NAME)); + const ScopedJSStringRef packageStr(JSStringCreateWithUTF8CString(APPLICATOIN_ATTRIBUTE_PACKAGE_NAME)); + const ScopedJSStringRef iconPathStr(JSStringCreateWithUTF8CString(APPLICATOIN_ATTRIBUTE_ICONF_PATH)); + const ScopedJSStringRef versionStr(JSStringCreateWithUTF8CString(APPLICATOIN_ATTRIBUTE_VERSION)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef nameData = JSObjectGetProperty(m_context, jsObject, nameStr.get(), NULL); + JSValueRef packageData = JSObjectGetProperty(m_context, jsObject, packageStr.get(), NULL); + JSValueRef iconPathData = JSObjectGetProperty(m_context, jsObject, iconPathStr.get(), NULL); + JSValueRef versionData = JSObjectGetProperty(m_context, jsObject, versionStr.get(), NULL); + + std::string name; + std::string package; + std::string iconPath; + std::string version; + + ApplicationInformationPtr result(new ApplicationInformation()); + if (!result) { + Throw(Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, nameData)) { + name = toString(nameData); + result->setName(name); + } + if (!JSValueIsUndefined(m_context, packageData)) { + package = toString(packageData); + result->setPackage(package); + } + if (!JSValueIsUndefined(m_context, iconPathData)) { + iconPath = toString(iconPathData); + result->setIconPath(iconPath); + } + if (!JSValueIsUndefined(m_context, versionData)) { + version = toString(versionData); + result->setVersion(version); + } + + return result; +} + +JSValueRef ApplicationConverter::toJSValueRef(const ApplicationInformationArrayPtr &arg) +{ + if(arg == NULL) + { + Throw(Commons::InvalidArgumentException); + } + return CommonsJavaScript::JSUtils::makeObject(m_context, JSApplicationInformationArray::getClassRef(), arg); +} + +ApplicationInformationArrayPtr ApplicationConverter::toApplicationInformationArray(const JSValueRef &jsValue) +{ + if(JSApplicationInformationArray::isObjectOfClass(m_context, jsValue)) + return JSApplicationInformationArray::getApplicationInformationArray(m_context, jsValue); + + ApplicationInformationArrayPtr result(new ApplicationInformationArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toApplicationInformation(element)); + } + return result; +} + +JSValueRef ApplicationConverter::toJSValueRef(const ApplicationServiceRequestPtr &arg) +{ + LogDebug("entered"); + return CommonsJavaScript::JSUtils::makeObject(m_context, JSApplicationServiceRequest::getClassRef(), arg); +} + +ApplicationServiceRequestPtr ApplicationConverter::toApplicationServiceRequest(const JSValueRef &jsValue) +{ + if(JSApplicationServiceRequest::isObjectOfClass(m_context, jsValue)) + return JSApplicationServiceRequest::getApplicationServiceRequest(m_context, jsValue); + + CommonsJavaScript::Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedApplicationServiceRequest, jsValue)) { + LogError("invalid properties in ApplicationServiceRequest object"); + ThrowMsg(Commons::ConversionException, "Wrong attribute"); + } + + const ScopedJSStringRef operationStr(JSStringCreateWithUTF8CString(APPLICATOIN_ATTRIBUTE_OPERATION)); + const ScopedJSStringRef uriStr(JSStringCreateWithUTF8CString(APPLICATOIN_ATTRIBUTE_URI)); + const ScopedJSStringRef mimeStr(JSStringCreateWithUTF8CString(APPLICATOIN_ATTRIBUTE_MIME)); + const ScopedJSStringRef packageStr(JSStringCreateWithUTF8CString(APPLICATOIN_ATTRIBUTE_PACKAGE_NAME)); + const ScopedJSStringRef extraDataStr(JSStringCreateWithUTF8CString(APPLICATOIN_ATTRIBUTE_EXTRADATA)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef jsoperation = JSObjectGetProperty(m_context, jsObject, operationStr.get(), NULL); + JSValueRef jsuri = JSObjectGetProperty(m_context, jsObject, uriStr.get(), NULL); + JSValueRef jsmime = JSObjectGetProperty(m_context, jsObject, mimeStr.get(), NULL); + JSValueRef jspackage = JSObjectGetProperty(m_context, jsObject, packageStr.get(), NULL); + JSValueRef jsextradata = JSObjectGetProperty(m_context, jsObject, extraDataStr.get(), NULL); + + std::string operation; + std::string uri; + std::string mime; + std::string package; + ApplicationServiceExtraDataArrayPtr extraDataArray; + + ApplicationServiceRequestPtr result(new ApplicationServiceRequest()); + if (!result) { + Throw(Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, jsoperation)) { + operation = toString(jsoperation); + LogDebug("operation : "<setOperation(operation); + } + + if (!JSValueIsUndefined(m_context, jsuri)) { + uri = toString(jsuri); + result->setUri(uri); + } + + if (!JSValueIsUndefined(m_context, jsmime)) { + mime = toString(jsmime); + result->setMime(mime); + } + + if (!JSValueIsUndefined(m_context, jspackage)) { + package = toString(jspackage); + LogDebug("package : "<setPackage(package); + } + + if (!JSValueIsUndefined(m_context, jsextradata)) { + extraDataArray = toApplicationServiceExtraDataArray(jsextradata); + result->setExtraDataArray(extraDataArray); + } + LogDebug("done"); + return result; +} + +JSValueRef ApplicationConverter::toJSValueRef(const ApplicationServiceReplyPtr &arg) +{ + LogDebug("entered"); + return CommonsJavaScript::JSUtils::makeObject(m_context, JSApplicationServiceReply::getClassRef(), arg); +} + +ApplicationServiceReplyPtr ApplicationConverter::toApplicationServiceReply(const JSValueRef &jsValue) +{ + if(JSApplicationServiceReply::isObjectOfClass(m_context, jsValue)) + return JSApplicationServiceReply::getApplicationServiceReply(m_context, jsValue); + + CommonsJavaScript::Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedApplicationServiceReply, jsValue)) { + LogError("invalid properties in ApplicationServiceReply object"); + ThrowMsg(Commons::ConversionException, "Wrong attribute"); + } + + const ScopedJSStringRef extraDataStr(JSStringCreateWithUTF8CString(APPLICATOIN_ATTRIBUTE_EXTRADATA)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef jsextradata = JSObjectGetProperty(m_context, jsObject, extraDataStr.get(), NULL); + + ApplicationServiceExtraDataArrayPtr extraDataArray; + + ApplicationServiceReplyPtr result(new ApplicationServiceReply()); + if (!result) { + Throw(Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, jsextradata)) { + extraDataArray = toApplicationServiceExtraDataArray(jsextradata); + result->setExtraDataArray(extraDataArray); + } + LogDebug("done"); + return result; +} + +JSValueRef ApplicationConverter::toJSValueRef(const ApplicationServiceExtraDataPtr &arg) +{ + LogDebug("entered"); + return CommonsJavaScript::JSUtils::makeObject(m_context, JSApplicationServiceExtraData::getClassRef(), arg); +} + +ApplicationServiceExtraDataPtr ApplicationConverter::toApplicationServiceExtraData(const JSValueRef &jsValue) +{ + if(JSApplicationServiceExtraData::isObjectOfClass(m_context, jsValue)) + return JSApplicationServiceExtraData::getApplicationServiceExtraData(m_context, jsValue); + + CommonsJavaScript::Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedApplicationServiceExtraData, jsValue)) { + LogError("invalid properties in contact object"); + ThrowMsg(Commons::ConversionException, "Wrong attribute"); + } + + const ScopedJSStringRef extraDataKeyStr(JSStringCreateWithUTF8CString(APPLICATOIN_ATTRIBUTE_EXTRA_KEY)); + const ScopedJSStringRef extraDataValueStr(JSStringCreateWithUTF8CString(APPLICATOIN_ATTRIBUTE_EXTRA_VALUE)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef extraDataKeyData = JSObjectGetProperty(m_context, jsObject, extraDataKeyStr.get(), NULL); + JSValueRef extraDataValueData = JSObjectGetProperty(m_context, jsObject, extraDataValueStr.get(), NULL); + + std::string extraDataKey; + std::string extraDataValue; + + ApplicationServiceExtraDataPtr result(new ApplicationServiceExtraData()); + if (!result) { + Throw(Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, extraDataKeyData)) { + extraDataKey = toString(extraDataKeyData); + result->setKey(extraDataKey); + } + + if (!JSValueIsUndefined(m_context, extraDataValueData)) { + extraDataValue = toString(extraDataValueData); + result->setValue(extraDataValue); + } + return result; +} + +JSValueRef ApplicationConverter::toJSValueRef(const ApplicationServiceExtraDataArrayPtr &arg) +{ + LogDebug("entered"); + return CommonsJavaScript::JSUtils::makeObject(m_context, JSApplicationServiceExtraDataArray::getClassRef(), arg); +} + +ApplicationServiceExtraDataArrayPtr ApplicationConverter::toApplicationServiceExtraDataArray(const JSValueRef &jsValue) +{ + if(JSApplicationServiceExtraDataArray::isObjectOfClass(m_context, jsValue)) + return JSApplicationServiceExtraDataArray::getApplicationServiceExtraDataArray(m_context, jsValue); + + ApplicationServiceExtraDataArrayPtr result(new ApplicationServiceExtraDataArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toApplicationServiceExtraData(element)); + } + return result; +} + +bool ApplicationConverter::initializeAllowedProperties() +{ + m_allowedApplicationInformation.push_back(APPLICATOIN_ATTRIBUTE_NAME); + m_allowedApplicationInformation.push_back(APPLICATOIN_ATTRIBUTE_PACKAGE_NAME); + m_allowedApplicationInformation.push_back(APPLICATOIN_ATTRIBUTE_ICONF_PATH); + m_allowedApplicationInformation.push_back(APPLICATOIN_ATTRIBUTE_VERSION); + + m_allowedApplicationServiceRequest.push_back(APPLICATOIN_ATTRIBUTE_OPERATION); + m_allowedApplicationServiceRequest.push_back(APPLICATOIN_ATTRIBUTE_URI); + m_allowedApplicationServiceRequest.push_back(APPLICATOIN_ATTRIBUTE_MIME); + m_allowedApplicationServiceRequest.push_back(APPLICATOIN_ATTRIBUTE_PACKAGE_NAME); + m_allowedApplicationServiceRequest.push_back(APPLICATOIN_ATTRIBUTE_EXTRADATA); + + m_allowedApplicationServiceReply.push_back(APPLICATOIN_ATTRIBUTE_EXTRADATA); + + m_allowedApplicationServiceExtraData.push_back(APPLICATOIN_ATTRIBUTE_EXTRA_KEY); + m_allowedApplicationServiceExtraData.push_back(APPLICATOIN_ATTRIBUTE_EXTRA_VALUE); + + return true; +} + +} +} +} diff --git a/src/standards/Tizen/Application/ApplicationConverter.h b/src/standards/Tizen/Application/ApplicationConverter.h new file mode 100755 index 0000000..c6a32d1 --- /dev/null +++ b/src/standards/Tizen/Application/ApplicationConverter.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_TIZEN_APPLICATION_CONVERTER_H_ +#define TIZENAPIS_TIZEN_APPLICATION_CONVERTER_H_ + +#include +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { +class ApplicationConverter : public WrtDeviceApis::CommonsJavaScript::Converter +{ +public: + using WrtDeviceApis::CommonsJavaScript::Converter::toJSValueRef; +public: + explicit ApplicationConverter(JSContextRef context); + virtual ~ApplicationConverter(); + JSValueRef toJSValueRef(const Api::Application::ApplicationInformationPtr &arg); + Api::Application::ApplicationInformationPtr toApplicationInformation(const JSValueRef &jsValue); + JSValueRef toJSValueRef(const Api::Application::ApplicationInformationArrayPtr &arg); + Api::Application::ApplicationInformationArrayPtr toApplicationInformationArray(const JSValueRef &jsValue); + JSValueRef toJSValueRef(const Api::Application::ApplicationServiceRequestPtr &arg); + Api::Application::ApplicationServiceRequestPtr toApplicationServiceRequest(const JSValueRef &jsValue); + JSValueRef toJSValueRef(const Api::Application::ApplicationServiceReplyPtr &arg); + Api::Application::ApplicationServiceReplyPtr toApplicationServiceReply(const JSValueRef &jsValue); + JSValueRef toJSValueRef(const Api::Application::ApplicationServiceExtraDataPtr &arg); + Api::Application::ApplicationServiceExtraDataPtr toApplicationServiceExtraData(const JSValueRef &jsValue); + JSValueRef toJSValueRef(const Api::Application::ApplicationServiceExtraDataArrayPtr &arg); + Api::Application::ApplicationServiceExtraDataArrayPtr toApplicationServiceExtraDataArray(const JSValueRef &jsValue); + + +private: + bool initializeAllowedProperties(); + static std::vector m_allowedApplicationInformation; + static std::vector m_allowedApplicationServiceRequest; + static std::vector m_allowedApplicationServiceReply; + static std::vector m_allowedApplicationServiceExtraData; + +}; + +typedef WrtDeviceApis::CommonsJavaScript::ConverterFactory ApplicationConverterFactory; +} +} +} +#endif diff --git a/src/standards/Tizen/Application/ApplicationListener.cpp b/src/standards/Tizen/Application/ApplicationListener.cpp new file mode 100755 index 0000000..8fa7708 --- /dev/null +++ b/src/standards/Tizen/Application/ApplicationListener.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include "JSApplicationInformation.h" +#include "JSApplicationEvent.h" +#include "ApplicationListener.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +using namespace std; +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Application; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +ApplicationListener& ApplicationListener::getInstance() +{ + static ApplicationListener instance; + return instance; +} + +ApplicationListener::ApplicationListener() : + WrtDeviceApis::Commons::EventListener(WrtDeviceApis::Commons::ThreadEnum::NULL_THREAD) +{ +} + +void ApplicationListener::onAnswerReceived(const EventInstalledApplicationChangedPtr& event) +{ + JSCallbackManagerPtr callbackManager = DPL::DynamicPointerCast(event->getPrivateData()); + JSContextRef context = callbackManager->getContext(); + Converter converter(context); + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + + Try + { + JSValueRef result = JSApplicationEvent::createJSObject(context, event->getEventCode(), event->getApplicationInformation()); + callbackManager->callOnSuccess(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error during function executing"); + } + } + else { + LogDebug("Operation failed. Exception code: " << event->getExceptionCode()); + JSValueRef errorObject = NULL; + + WrtDeviceApis::Commons::ExceptionCodes::Enumeration exception = event->getExceptionCode(); + switch(exception){ + default: + errorObject = JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::UNKNOWN_ERROR,"unknown error"); + break; + } + callbackManager->callOnError(errorObject); + } +} + +} +} +} + diff --git a/src/standards/Tizen/Application/ApplicationListener.h b/src/standards/Tizen/Application/ApplicationListener.h new file mode 100755 index 0000000..5c47e46 --- /dev/null +++ b/src/standards/Tizen/Application/ApplicationListener.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_TIZEN_APPLICATION_LISTENER_H_ +#define TIZENAPIS_TIZEN_APPLICATION_LISTENER_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { +class ApplicationListener : + public WrtDeviceApis::Commons::EventListener +{ + public: + static ApplicationListener& getInstance(); + void onAnswerReceived(const Api::Application::EventInstalledApplicationChangedPtr& event); + + protected: + ApplicationListener(); +}; + +} +} +} +#endif \ No newline at end of file diff --git a/src/standards/Tizen/Application/ApplicationServiceReplyCallback.h b/src/standards/Tizen/Application/ApplicationServiceReplyCallback.h new file mode 100755 index 0000000..e5a6ee0 --- /dev/null +++ b/src/standards/Tizen/Application/ApplicationServiceReplyCallback.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_TIZEN_APPLICATION_SERVICE_REPLY_CALLBACK_H_ +#define TIZENAPIS_TIZEN_APPLICATION_SERVICE_REPLY_CALLBACK_H_ + +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { +struct ApplicationServiceReplyCallback +{ + JSValueRef onsuccess; + JSValueRef onfail; + JSValueRef oncancel; + + ApplicationServiceReplyCallback() : + onsuccess(NULL), + onfail(NULL), + oncancel(NULL) + { + } +}; +} +} +} +#endif diff --git a/src/standards/Tizen/Application/CMakeLists.txt b/src/standards/Tizen/Application/CMakeLists.txt new file mode 100755 index 0000000..7deed12 --- /dev/null +++ b/src/standards/Tizen/Application/CMakeLists.txt @@ -0,0 +1,35 @@ +set(TARGET_NAME "wrt-plugins-tizen-1.0-application") +set(DESTINATION_NAME "tizen-1.0-application") +include_directories(${INCLUDES_PLATFORM_IMPLEMENTATION_APPLICATION}) + +set(SRCS +# ${SRCS_PLATFORM_API_WRT_WRAPPER} + ${SRCS_PLATFORM_API_APPLICATION} + ${SRCS_PLATFORM_IMPLEMENTATION_APPLICATION} + plugin_initializer.cpp + plugin_config.cpp + ApplicationAnswerReceiver.cpp + ApplicationListener.cpp + ApplicationConverter.cpp + JSApplication.cpp + JSApplicationInformation.cpp + JSApplicationInformationArray.cpp + JSApplicationEvent.cpp + JSApplicationServiceExtraData.cpp + JSApplicationServiceExtraDataArray.cpp + JSApplicationServiceRequest.cpp + JSApplicationServiceReply.cpp + LaunchServicePrivateData.cpp + ../Common/JSTizenException.cpp + ../Common/TizenExceptionData.cpp + ../Common/JSTizenExceptionFactory.cpp +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMON} + ${LIBS_PLATFORM_IMPLEMENTATION_APPLICATION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION ${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_NAME}) diff --git a/src/standards/Tizen/Application/JSApplication.cpp b/src/standards/Tizen/Application/JSApplication.cpp new file mode 100755 index 0000000..89f8399 --- /dev/null +++ b/src/standards/Tizen/Application/JSApplication.cpp @@ -0,0 +1,549 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "plugin_config.h" +#include "ApplicationAnswerReceiver.h" +#include "ApplicationListener.h" +#include "JSApplication.h" +#include "ApplicationConverter.h" +#include "ApplicationServiceReplyCallback.h" +#include "LaunchServicePrivateData.h" +#include "JSApplicationServiceRequest.h" +#include "JSApplicationServiceReply.h" +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +using namespace std; +using namespace DPL; +using namespace TizenApis::Api::Application; +using namespace TizenApis::Commons; + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +JSClassRef JSApplication::m_jsClassRef = NULL; + +JSClassDefinition JSApplication::m_classInfo = { + 0, + kJSClassAttributeNone, + "application", + NULL, + NULL, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty,Geolocation + NULL, //getPropertyNames, + NULL, + NULL, + hasInstance, + NULL +}; + +JSStaticFunction JSApplication::m_function[] = { + { "listInstalledApplications",JSApplication::listInstalledApplications,kJSPropertyAttributeNone }, + { "listRunningApplications",JSApplication::listRunningApplications,kJSPropertyAttributeNone }, + { "getApplicationInformation",JSApplication::getApplicationInformation,kJSPropertyAttributeNone }, + { "addApplicationListChangeListener",JSApplication::addApplicationListChangeListener,kJSPropertyAttributeNone }, + { "removeApplicationListChangeListener",JSApplication::removeApplicationListChangeListener,kJSPropertyAttributeNone }, + { "launchService",JSApplication::launchService,kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef JSApplication::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSApplication::getClassInfo() { + return &m_classInfo; +} + +void JSApplication::initialize(JSContextRef context, JSObjectRef object) { + JSApplicationPriv* priv = static_cast(JSObjectGetPrivate(object)); + assert(!priv && "Invalid object creation."); + IApplicationPtr applications(ApplicationFactory::getInstance().createApplication()); + priv = new JSApplicationPriv(context, applications); + if (!JSObjectSetPrivate(object, static_cast(priv))) { + LogError("Object can't store private data."); + delete priv; + } +} + +void JSApplication::finalize(JSObjectRef object) { + JSApplicationPriv* priv = static_cast (JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + +bool JSApplication::hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSApplication::listInstalledApplications(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + JSApplicationPriv *priv = static_cast (JSObjectGetPrivate(thisObject)); + assert(priv && "Invalid private pointer."); + JSContextRef gContext = priv->getContext(); + + AceSecurityStatus status = APPLICATION_CHECK_ACCESS( + gContext, + APPLICATION_FUNCTION_API_LIST_INSTALLED_APPLICATIONS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + + if ((argumentCount == 0) || + (JSValueIsNull(context, + arguments[0]) || + JSValueIsUndefined(context, + arguments[0]) || + !JSObjectIsFunction(context, + converter->toJSObjectRef(arguments[0]))) || + (argumentCount > 1 && + !JSValueIsNull(context, + arguments[1]) && + !JSValueIsUndefined(context, + arguments[1]) && + !JSObjectIsFunction(context, + converter->toJSObjectRef(arguments[1])))) { + LogError("Wrong callbacks parameters"); + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::TYPE_MISMATCH_ERROR, "Type mistmatch error"); + } + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + callbackManager->setOnSuccess(arguments[0]); + if (argumentCount > 1) + callbackManager->setOnError(arguments[1]); + + EventListInstalledApplicationsPtr event(new EventListInstalledApplications()); + Try{ + IApplicationPtr applications(priv->getObject()); + event->setEventType(EventListInstalledApplications::APPMANAGER_LIST_INSTALLED_APPLICATIONS); + event->setPrivateData(StaticPointerCast(callbackManager)); + event->setForAsynchronousCall(new ApplicationAnswerReceiver(callbackManager)); + applications->listApplications(event); + }Catch (WrtDeviceApis::Commons::ConversionException){ + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::TYPE_MISMATCH_ERROR, "Type mistmatch error"); + }Catch (WrtDeviceApis::Commons::PendingOperationException){ + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::INVALID_VALUES_ERROR,"Pending operation failed")); + return JSValueMakeUndefined(context); + }Catch (WrtDeviceApis::Commons::InvalidArgumentException){ + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::INVALID_VALUES_ERROR,"Invalid value error")); + return JSValueMakeUndefined(context); + }Catch (WrtDeviceApis::Commons::NullPointerException){ + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::UNKNOWN_ERROR,"Unknown error")); + return JSValueMakeUndefined(context); + }Catch(WrtDeviceApis::Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage() << " Code: " << _rethrown_exception.getCode()); + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::UNKNOWN_ERROR, "Unknown error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplication::listRunningApplications(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + JSApplicationPriv *priv = static_cast (JSObjectGetPrivate(thisObject)); + + assert(priv && "Invalid private pointer."); + JSContextRef gContext = priv->getContext(); + + AceSecurityStatus status = APPLICATION_CHECK_ACCESS( + gContext, + APPLICATION_FUNCTION_API_LIST_RUNNING_APPLICATIONS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + + if ((argumentCount == 0) || + (JSValueIsNull(context, + arguments[0]) || + JSValueIsUndefined(context, + arguments[0]) || + !JSObjectIsFunction(context, + converter->toJSObjectRef(arguments[0]))) || + (argumentCount > 1 && + !JSValueIsNull(context, + arguments[1]) && + !JSValueIsUndefined(context, + arguments[1]) && + !JSObjectIsFunction(context, + converter->toJSObjectRef(arguments[1])))) { + LogError("Wrong callbacks parameters"); + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::TYPE_MISMATCH_ERROR, "Type mistmatch error"); + } + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + callbackManager->setOnSuccess(arguments[0]); + if (argumentCount > 1) + callbackManager->setOnError(arguments[1]); + + EventListInstalledApplicationsPtr event(new EventListInstalledApplications()); + Try{ + IApplicationPtr applications(priv->getObject()); + event->setEventType(EventListInstalledApplications::APPMANAGER_LIST_RUNNING_APPLICATIONS); + event->setPrivateData(StaticPointerCast(callbackManager)); + event->setForAsynchronousCall(new ApplicationAnswerReceiver(callbackManager)); + applications->listApplications(event); + }Catch (WrtDeviceApis::Commons::ConversionException){ + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::TYPE_MISMATCH_ERROR, "Type mistmatch error"); + }Catch (WrtDeviceApis::Commons::PendingOperationException){ + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::INVALID_VALUES_ERROR,"Pending operation failed")); + return JSValueMakeUndefined(context); + }Catch (WrtDeviceApis::Commons::InvalidArgumentException){ + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::INVALID_VALUES_ERROR,"Invalid value error")); + return JSValueMakeUndefined(context); + }Catch (WrtDeviceApis::Commons::NullPointerException){ + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::UNKNOWN_ERROR,"Unknown error")); + return JSValueMakeUndefined(context); + }Catch(WrtDeviceApis::Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage() << " Code: " << _rethrown_exception.getCode()); + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::UNKNOWN_ERROR, "Unknown error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplication::getApplicationInformation(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + JSApplicationPriv *priv = static_cast (JSObjectGetPrivate(thisObject)); + + assert(priv && "Invalid private pointer."); + AceSecurityStatus status = APPLICATION_CHECK_ACCESS( + priv->getContext(), + APPLICATION_FUNCTION_API_GET_APPLICATION_INFORMATION); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + + if(JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0])){ + LogError("Wrong package " << JSValueIsNull(context, arguments[0]) <<", "<toString( arguments[0] ); + IApplicationPtr applications(priv->getObject()); + event->setForSynchronousCall(); + event->setPackage(package); + applications->getApplicationInformation(event); + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::NotFoundException) { + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::NOT_FOUND_ERROR, "Given package is not found"); + } + jsobj = converter->toJSValueRef(event->getApplicationInformation()); + }Catch (WrtDeviceApis::Commons::ConversionException){ + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::TYPE_MISMATCH_ERROR, "Type mistmatch error"); + }Catch (WrtDeviceApis::Commons::InvalidArgumentException){ + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::INVALID_VALUES_ERROR,"Invalid value error"); + }Catch (WrtDeviceApis::Commons::NullPointerException){ + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::UNKNOWN_ERROR, "Unknown error"); + }Catch(WrtDeviceApis::Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage() << " Code: " << _rethrown_exception.getCode()); + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::UNKNOWN_ERROR, "Unknown error"); + } + return jsobj; +} + +JSValueRef JSApplication::addApplicationListChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + JSApplicationPriv *priv = static_cast (JSObjectGetPrivate(thisObject)); + + assert(priv && "Invalid private pointer."); + AceSecurityStatus status = APPLICATION_CHECK_ACCESS( + priv->getContext(), + APPLICATION_FUNCTION_API_ADD_APPLICATION_LIST_CHANGE_LISTENER); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + CommonsJavaScript::Converter converter(context); + + if ((argumentCount == 0) || + (JSValueIsNull(context, + arguments[0]) || + JSValueIsUndefined(context, + arguments[0]) || + !JSObjectIsFunction(context, + converter.toJSObjectRef(arguments[0]))) || + (argumentCount > 1 && + !JSValueIsNull(context, + arguments[1]) && + !JSValueIsUndefined(context, + arguments[1]) && + !JSObjectIsFunction(context, + converter.toJSObjectRef(arguments[1])))) { + LogError("Wrong callbacks parameters"); + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::TYPE_MISMATCH_ERROR, "Type mistmatch error"); + } + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(priv->getContext()); + callbackManager->setOnSuccess(arguments[0]); + if (argumentCount >= 2) + callbackManager->setOnError(arguments[1]); + + Try{ + IApplicationPtr applications(priv->getObject()); + EventInstalledApplicationChangedEmitterPtr emitter(new EventInstalledApplicationChangedEmitter); + emitter->setListener(&ApplicationListener::getInstance()); + emitter->setEventPrivateData(StaticPointerCast(callbackManager)); + unsigned long id = applications->addApplicationListChangeListener(emitter); + LogInfo("id = "<callOnError(JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::INVALID_VALUES_ERROR,"Invalid value error")); + return JSValueMakeUndefined(context); + }Catch (WrtDeviceApis::Commons::NullPointerException){ + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::UNKNOWN_ERROR,"Unknown error")); + return JSValueMakeUndefined(context); + }Catch(WrtDeviceApis::Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage() << " Code: " << _rethrown_exception.getCode()); + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::UNKNOWN_ERROR, "Unknown error"); + } +} + +JSValueRef JSApplication::removeApplicationListChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + JSApplicationPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + assert(priv && "Invalid private pointer."); + AceSecurityStatus status = APPLICATION_CHECK_ACCESS( + priv->getContext(), + APPLICATION_FUNCTION_API_REMOVE_APPLICATION_LIST_CHANGE_LISTENER); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + CommonsJavaScript::Converter converter(context); + Try + { + IApplicationPtr applications = priv->getObject(); + assert(applications && "Application object not present."); + + if (argumentCount < 1) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + long id = converter.toLong(arguments[0]); + applications->removeApplicationListChangeListener(id); + }Catch (WrtDeviceApis::Commons::InvalidArgumentException){ + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::TYPE_MISMATCH_ERROR, "Type mistmatch error"); + }Catch (WrtDeviceApis::Commons::ConversionException){ + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::TYPE_MISMATCH_ERROR, "Type mistmatch error"); + }Catch (WrtDeviceApis::Commons::NullPointerException){ + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::UNKNOWN_ERROR, "Unknown error"); + }Catch(WrtDeviceApis::Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage() << " Code: " << _rethrown_exception.getCode()); + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::UNKNOWN_ERROR, "Unknown error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplication::launchService(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogInfo("launchService <<<"); + LogDebug("argumentConunt:" << argumentCount); + JSApplicationPriv *priv = static_cast (JSObjectGetPrivate(thisObject)); + assert(priv && "Invalid private pointer."); + AceSecurityStatus status = APPLICATION_CHECK_ACCESS( + priv->getContext(), + APPLICATION_FUNCTION_API_LAUNCH_SERVICE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + JSContextRef gContext = priv->getContext(); + + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + + if ((argumentCount < 2) || + (JSValueIsNull(context, + arguments[0]) || + JSValueIsUndefined(context, + arguments[0]) || + JSValueIsNull(context, + arguments[1]) || + JSValueIsUndefined(context, + arguments[1]) || + !JSObjectIsFunction(context, + converter->toJSObjectRef(arguments[1]))) || + (argumentCount > 2 && + !JSValueIsNull(context, + arguments[2]) && + !JSValueIsUndefined(context, + arguments[2]) && + !JSObjectIsFunction(context, + converter->toJSObjectRef(arguments[2])))) { + LogError("Wrong parameters"); + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::TYPE_MISMATCH_ERROR, "Type mistmatch error"); + } + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + callbackManager->setOnSuccess(arguments[1]); + if (argumentCount > 2) + callbackManager->setOnError(arguments[2]); + + try { + ApplicationServiceRequestPtr appService; + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + appService = converter->toApplicationServiceRequest(arguments[0]); + + LogDebug("after toApplicationServiceRequest()"); + // arguments[3] : optional , onsuccess, onfail, oncancel + JSCallbackManagerPtr replyCallbackManager; + JSCallbackManagerPtr replyCancelCallbackManager; + if( argumentCount >3) + { + CommonsJavaScript::Validator validator(gContext); + ApplicationServiceReplyCallback result; + + JSObjectRef obj = JSValueToObject(context, arguments[3],NULL); + + result.onsuccess = JSUtils::getJSProperty( + context, obj, "onsuccess"); + if (!validator.isNullOrUndefined(result.onsuccess) && + !validator.isCallback(result.onsuccess)) { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Not a valid callback."); + } + + result.onfail = JSUtils::getJSProperty( + context, obj, "onfail"); + if (!validator.isNullOrUndefined(result.onfail) && + !validator.isCallback(result.onfail)) { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Not a valid callback."); + } + + result.oncancel = JSUtils::getJSProperty( + context, obj, "oncancel"); + if (!validator.isNullOrUndefined(result.oncancel) && + !validator.isCallback(result.oncancel)) { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Not a valid callback."); + } + + if(result.onsuccess || result.onfail) + { + replyCallbackManager = JSCallbackManager::createObject(priv->getContext(), + result.onsuccess, result.onfail); + replyCallbackManager->setObject(thisObject); + } + + if(result.oncancel) + { + replyCancelCallbackManager = JSCallbackManager::createObject(priv->getContext(), + result.oncancel, NULL); + replyCancelCallbackManager->setObject(thisObject); + } + + } + + LogDebug("replyCallback, replyCancel"<getObject()); + + event->setPrivateData(StaticPointerCast (privateData)); + event->setServiceRequest(appService); + event->setForAsynchronousCall(new ApplicationAnswerReceiver(privateData)); + + applications->launchService(event); + }Catch (WrtDeviceApis::Commons::ConversionException){ + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::TYPE_MISMATCH_ERROR, "Type mistmatch error"); + }Catch (WrtDeviceApis::Commons::UnsupportedException){ + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::NOT_SUPPORTED_ERROR, "Not supported"); + }Catch (WrtDeviceApis::Commons::InvalidArgumentException){ + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::INVALID_VALUES_ERROR,"Invalid value error")); + return JSValueMakeUndefined(context); + }Catch (WrtDeviceApis::Commons::NullPointerException){ + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,JSTizenException::UNKNOWN_ERROR,"Unknown error")); + return JSValueMakeUndefined(context); + }Catch(WrtDeviceApis::Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage() << " Code: " << _rethrown_exception.getCode()); + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::UNKNOWN_ERROR, "Unknown error"); + } + + return JSValueMakeUndefined(context); +} + +} +} +} diff --git a/src/standards/Tizen/Application/JSApplication.h b/src/standards/Tizen/Application/JSApplication.h new file mode 100755 index 0000000..b3247ae --- /dev/null +++ b/src/standards/Tizen/Application/JSApplication.h @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_JS_APPLICATION_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSApplicationPriv; + +class JSApplication { +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + /** + * Gets the list of installed packages. + */ + static JSValueRef listInstalledApplications(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Gets the list of running packages. + */ + static JSValueRef listRunningApplications(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Gets the application information of based on the package name. + */ + static JSValueRef getApplicationInformation(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Watch for changes on installed applicaiton. + */ + static JSValueRef addApplicationListChangeListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Unset installed Applications listener + */ + static JSValueRef removeApplicationListChangeListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Launch a service + */ + static JSValueRef launchService(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + static JSClassRef m_jsClassRef; + +}; + +} +} +} +#endif diff --git a/src/standards/Tizen/Application/JSApplicationEvent.cpp b/src/standards/Tizen/Application/JSApplicationEvent.cpp new file mode 100755 index 0000000..8dfbaa4 --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationEvent.cpp @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include "JSApplicationEvent.h" +#include "JSApplicationInformation.h" +#include "ApplicationConverter.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace Api::Application; +using namespace TizenApis::Commons; + + +namespace { +const char* APPLICATION_EVENT_CODE = "code"; +const char* APPLICATION_EVENT_APPLICATIONINFORMATION = "applicationInformation"; +} + +JSClassRef JSApplicationEvent::m_jsClassRef = NULL; + +JSClassDefinition JSApplicationEvent::m_classInfo = { + 0, + kJSClassAttributeNone, + "ApplicationEvent", + 0, + m_property, + 0, + initialize, + finalize, + NULL, //HasProperty, + getProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, + NULL, //ConvertToType +}; + +JSStaticValue JSApplicationEvent::m_property[] = { + { APPLICATION_EVENT_CODE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { APPLICATION_EVENT_APPLICATIONINFORMATION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassDefinition* JSApplicationEvent::getClassInfo() +{ + return &m_classInfo; +} + +const JSClassRef JSApplicationEvent::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +JSObjectRef JSApplicationEvent::createJSObject(JSContextRef context, + const std::string eventCode, + const ApplicationInformationPtr &appinfo) +{ + ApplicationEventPtr privateData = ApplicationEventPtr(new ApplicationEvent()); + privateData->setCode(eventCode); + privateData->setApplicationInformation(appinfo); + JSApplicationEventPriv *priv = new JSApplicationEventPriv(context, privateData); + JSObjectRef jsObjRef = JSObjectMake(context, getClassRef(), static_cast(priv)); + if (NULL == jsObjRef) { + LogError("object creation error"); + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Can not new an object"); + } + return jsObjRef; +} + +void JSApplicationEvent::initialize(JSContextRef context,JSObjectRef object) +{ +} + +void JSApplicationEvent::finalize(JSObjectRef object) +{ +} + +JSValueRef JSApplicationEvent::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + JSApplicationEventPriv *priv = + static_cast(JSObjectGetPrivate(object)); + assert(priv && "Private object not set."); + + Try { + ApplicationEventPtr appEvent = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, APPLICATION_EVENT_CODE)) { + LogDebug( + "JSApplicationEvent::getProperty ::code " <getCode()); + return convert.toJSValueRef(appEvent->getCode()); + }else if (JSStringIsEqualToUTF8CString(propertyName, + APPLICATION_EVENT_APPLICATIONINFORMATION)) { + LogDebug( + "JSApplicationEvent::getProperty ::applicationInformation"); + + ApplicationInformationPtr appinfo = appEvent->getApplicationInformation(); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + JSValueRef result = converter->toJSValueRef(appinfo); + + return result; + } + else + { + LogError("wrong property"); + } + } + Catch(WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception,JSTizenException::UNKNOWN_ERROR, "Unknown error"); + } + return JSValueMakeUndefined(context); +} + +bool JSApplicationEvent::hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} +} +} +} diff --git a/src/standards/Tizen/Application/JSApplicationEvent.h b/src/standards/Tizen/Application/JSApplicationEvent.h new file mode 100755 index 0000000..2de69f4 --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationEvent.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_JS_APPLICATION_EVENT_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_EVENT_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject JSApplicationEventPriv; + +class JSApplicationEvent { +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + /** + * create an JSObject for callback function(onAnswerReceived). + */ + static JSObjectRef createJSObject(JSContextRef context, + const std::string eventCode, + const Api::Application::ApplicationInformationPtr &appinfo); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception); + + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + +}; + +} +} +} +#endif diff --git a/src/standards/Tizen/Application/JSApplicationInformation.cpp b/src/standards/Tizen/Application/JSApplicationInformation.cpp new file mode 100755 index 0000000..36cea3a --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationInformation.cpp @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "JSApplicationInformation.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +using namespace WrtDeviceApis; +using namespace Api::Application; +using namespace TizenApis::Commons; + + +namespace { +const char* APPLICATION_INFORMATION_NAME = "name"; +const char* APPLICATION_INFORMATION_PACKAGE_NAME = "packageName"; +const char* APPLICATION_INFORMATION_ICONPATH = "iconPath"; +const char* APPLICATION_INFORMATION_VERSION = "version"; + +} //private namespace + +JSClassRef JSApplicationInformation::m_classRef = NULL; + +JSClassDefinition JSApplicationInformation::m_classInfo = { + 0, + kJSClassAttributeNone, + "ApplicationInformation", + 0, + m_property, + 0, + initialize, + finalize, + NULL, //HasProperty, + NULL, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + +JSStaticValue JSApplicationInformation::m_property[] = { + { APPLICATION_INFORMATION_NAME, getName, setName, kJSPropertyAttributeReadOnly }, + { APPLICATION_INFORMATION_PACKAGE_NAME, getPackage, setPackage, kJSPropertyAttributeReadOnly }, + { APPLICATION_INFORMATION_ICONPATH, getIconPath, setIconPath, kJSPropertyAttributeReadOnly }, + { APPLICATION_INFORMATION_VERSION, getVersion, setVersion, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSApplicationInformation::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSApplicationInformation::createJSObject(JSContextRef context, + const std::string &name, + const std::string &package, + const std::string &iconPath, + const std::string &version) +{ + ApplicationInformationPtr privateData = ApplicationInformationPtr(new ApplicationInformation()); + + privateData->setName(name); + privateData->setPackage(package); + privateData->setIconPath(iconPath); + privateData->setVersion(version); + JSApplicationInformationPriv *priv = new JSApplicationInformationPriv(context, privateData); + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast(priv)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +void JSApplicationInformation::initialize(JSContextRef context, JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSApplicationInformation::finalize(JSObjectRef object) +{ +} + +bool JSApplicationInformation::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ApplicationInformationPtr JSApplicationInformation::getPrivData(JSObjectRef object) +{ + JSApplicationInformationPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + ApplicationInformationPtr result = priv->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + return result; +} + +ApplicationInformationPtr + JSApplicationInformation::getApplicationInformation(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSApplicationInformationPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +JSValueRef JSApplicationInformation::getName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + CommonsJavaScript::Converter converter(context); + ApplicationInformationPtr privateData = getPrivData(object); + return converter.toJSValueRef(privateData->getName()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSApplicationInformation::setName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef name, + JSValueRef* exception) +{ + Try + { + ApplicationInformationPtr privateData = getPrivData(object); + CommonsJavaScript::Converter converter(context); + privateData->setName(converter.toString(name)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception,JSTizenException::INVALID_VALUES_ERROR, "Invalid value error"); + return false; +} + +JSValueRef JSApplicationInformation::getPackage(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + CommonsJavaScript::Converter converter(context); + ApplicationInformationPtr privateData = getPrivData(object); + return converter.toJSValueRef(privateData->getPackage()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSApplicationInformation::setPackage(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef package, + JSValueRef* exception) +{ + Try + { + ApplicationInformationPtr privateData = getPrivData(object); + CommonsJavaScript::Converter converter(context); + privateData->setPackage(converter.toString(package)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception,JSTizenException::INVALID_VALUES_ERROR, "Invalid value error"); + return false; +} + +JSValueRef JSApplicationInformation::getIconPath(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + CommonsJavaScript::Converter converter(context); + ApplicationInformationPtr privateData = getPrivData(object); + return converter.toJSValueRef(privateData->getIconPath()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSApplicationInformation::setIconPath(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef iconPath, + JSValueRef* exception) +{ + Try + { + ApplicationInformationPtr privateData = getPrivData(object); + CommonsJavaScript::Converter converter(context); + privateData->setIconPath(converter.toString(iconPath)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception,JSTizenException::INVALID_VALUES_ERROR, "Invalid value error"); + return false; +} + +JSValueRef JSApplicationInformation::getVersion(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + CommonsJavaScript::Converter converter(context); + ApplicationInformationPtr privateData = getPrivData(object); + return converter.toJSValueRef(privateData->getVersion()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSApplicationInformation::setVersion(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef version, + JSValueRef* exception) +{ + Try + { + ApplicationInformationPtr privateData = getPrivData(object); + CommonsJavaScript::Converter converter(context); + privateData->setVersion(converter.toString(version)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception,JSTizenException::INVALID_VALUES_ERROR, "Invalid value error"); + return false; +} + + +} +} +} diff --git a/src/standards/Tizen/Application/JSApplicationInformation.h b/src/standards/Tizen/Application/JSApplicationInformation.h new file mode 100755 index 0000000..92167b9 --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationInformation.h @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_JS_APPLICATION_INFORMATION_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_INFORMATION_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject JSApplicationInformationPriv; + +class JSApplicationInformation { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context, + const std::string &name, + const std::string &package, + const std::string &iconPath, + const std::string &version); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static Api::Application::ApplicationInformationPtr + getApplicationInformation(JSContextRef context, JSValueRef value); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static Api::Application::ApplicationInformationPtr getPrivData(JSObjectRef object); + + static JSValueRef getName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef name, + JSValueRef* exception); + + static JSValueRef getPackage(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setPackage(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef package, + JSValueRef* exception); + +static JSValueRef getIconPath(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + +static bool setIconPath(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef iconPath, + JSValueRef* exception); + +static JSValueRef getVersion(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + +static bool setVersion(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef version, + JSValueRef* exception); + +}; + +} +} +} +#endif diff --git a/src/standards/Tizen/Application/JSApplicationInformationArray.cpp b/src/standards/Tizen/Application/JSApplicationInformationArray.cpp new file mode 100755 index 0000000..eb5a65a --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationInformationArray.cpp @@ -0,0 +1,565 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "JSApplicationInformationArray.h" +#include "ApplicationConverter.h" + + +namespace { +const char* FUNCTION_CONCAT = "concat"; +const char* FUNCTION_JOIN = "join"; +const char* FUNCTION_POP = "pop"; +const char* FUNCTION_PUSH = "push"; +const char* FUNCTION_REVERSE = "reverse"; +const char* FUNCTION_SHIFT = "shift"; +const char* FUNCTION_SLICE = "slice"; +const char* FUNCTION_SORT = "sort"; +const char* FUNCTION_SPLICE = "splice"; +const char* FUNCTION_TOSTRING = "toString"; +const char* FUNCTION_UNSHIFT = "unshift"; +const char* FUNCTION_VALUEOF = "valueOf"; +const char *ARRAY = "Array"; +const char *ATTRIBUTE_LENGTH = "length"; +} + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +using namespace Api::Application; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::CommonsJavaScript; + +JSClassDefinition JSApplicationInformationArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSApplicationInformationArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSApplicationInformationArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSApplicationInformationArray::m_jsClassRef = JSClassCreate( + JSApplicationInformationArray::getClassInfo()); + +JSValueRef JSApplicationInformationArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + JSApplicationInformationArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ApplicationInformationArrayPtr privateDatas = priv->getObject(); + if (privateDatas) { + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + return converter->toJSValueRef(privateDatas->size()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSApplicationInformationArray::createArray(JSContextRef context, + const ApplicationInformationArrayPtr &privateDatas) +{ + JSApplicationInformationArrayPriv *priv = new JSApplicationInformationArrayPriv(context, privateDatas); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSApplicationInformationArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSApplicationInformationArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +bool JSApplicationInformationArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ApplicationInformationArrayPtr + JSApplicationInformationArray::getApplicationInformationArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSApplicationInformationArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSApplicationInformationArray::initialize(JSContextRef context, + JSObjectRef object) +{ + +} + +void JSApplicationInformationArray::finalize(JSObjectRef object) +{ + JSApplicationInformationArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSApplicationInformationArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSApplicationInformationArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ApplicationInformationArrayPtr privateDatas = priv->getObject(); + if (index < privateDatas->size()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSApplicationInformationArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSApplicationInformationArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ApplicationInformationArrayPtr privateDatas = priv->getObject(); + if (index < privateDatas->size()) { + ApplicationInformationPtr result = privateDatas->at(index); + if (result) { + return converter->toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSApplicationInformationArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + ApplicationInformationPtr privateData; + if (!JSValueIsUndefined(context, value)) { + privateData = converter->toApplicationInformation(value); + } + JSApplicationInformationArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ApplicationInformationArrayPtr privateDatas = priv->getObject(); + if (!privateDatas) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (privateDatas->size() <= index) { + privateDatas->resize(index + 1); + } + (*privateDatas)[index] = privateData; + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + JSDOMExceptionFactory::TypeMismatchException.make(context, exception); + } + return false; +} + +JSValueRef JSApplicationInformationArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + Try + { + ApplicationInformationArrayPtr privateDatas = ApplicationInformationArrayPtr(new ApplicationInformationArray()); + JSApplicationInformationArrayPriv *newPrivateObject = new JSApplicationInformationArrayPriv(context, privateDatas); + JSValueRef result = JSObjectMake(context, getClassRef(), newPrivateObject); + + //copy current privateDatas + JSApplicationInformationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationInformationArrayPtr currentApplicationInformations = priv->getObject(); + for (size_t i = 0; i < currentApplicationInformations->size(); ++i) { + privateDatas->push_back(currentApplicationInformations->at(i)); + } + + //copy submitted arrays + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + privateDatas->push_back(converter->toApplicationInformation(att)); + } + } + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSDOMExceptionFactory::TypeMismatchException.make(context, exception); +} + +JSValueRef JSApplicationInformationArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + Try + { + std::string result; + std::string separator(","); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + JSApplicationInformationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationInformationArrayPtr currentApplicationInformations = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentApplicationInformations->size(); ++i) { + if (i != 0) { + result += separator; + } + //FIXME : to be changed to support join + //result += currentApplicationInformations->at(i); + } + return converter->toJSValueRef(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSDOMExceptionFactory::TypeMismatchException.make(context, exception); +} + +JSValueRef JSApplicationInformationArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + Try + { + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + JSApplicationInformationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationInformationArrayPtr currentApplicationInformations = priv->getObject(); + if (currentApplicationInformations->size() > 0) { + ApplicationInformationPtr result = currentApplicationInformations->at( + currentApplicationInformations->size() - 1); + currentApplicationInformations->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplicationInformationArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + Try + { + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + JSApplicationInformationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationInformationArrayPtr currentApplicationInformations = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentApplicationInformations->push_back(converter->toApplicationInformation(arguments[i])); + } + return converter->toJSValueRef(currentApplicationInformations->size()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSDOMExceptionFactory::TypeMismatchException.make(context, exception); +} + +JSValueRef JSApplicationInformationArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + Try + { + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + JSApplicationInformationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationInformationArrayPtr currentApplicationInformations = priv->getObject(); + std::reverse(currentApplicationInformations->begin(), currentApplicationInformations->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplicationInformationArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + Try + { + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + JSApplicationInformationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationInformationArrayPtr currentApplicationInformations = priv->getObject(); + if (currentApplicationInformations->size() > 0) { + ApplicationInformationPtr result = currentApplicationInformations->at(0); + currentApplicationInformations->erase(currentApplicationInformations->begin()); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplicationInformationArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + ApplicationInformationArrayPtr privateDatas = ApplicationInformationArrayPtr(new ApplicationInformationArray()); + JSApplicationInformationArrayPriv *newPrivateObject = new JSApplicationInformationArrayPriv( + context, + privateDatas); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current privateDatas + JSApplicationInformationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationInformationArrayPtr currentApplicationInformations = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentApplicationInformations->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentApplicationInformations->size()) { + last = currentApplicationInformations->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + privateDatas->push_back(currentApplicationInformations->at(i)); + } + + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSDOMExceptionFactory::TypeMismatchException.make(context, exception); +} + +JSValueRef JSApplicationInformationArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + Try + { + //ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + JSApplicationInformationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationInformationArrayPtr currentApplicationInformations = priv->getObject(); + std::sort(currentApplicationInformations->begin(), currentApplicationInformations->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplicationInformationArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplicationInformationArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSApplicationInformationArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplicationInformationArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + return JSValueMakeUndefined(context); +} +} +} +} diff --git a/src/standards/Tizen/Application/JSApplicationInformationArray.h b/src/standards/Tizen/Application/JSApplicationInformationArray.h new file mode 100755 index 0000000..b16efc4 --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationInformationArray.h @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_JS_APPLICATION_INFORMATION_ARRAY_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_INFORMATION_ARRAY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSApplicationInformationArrayPriv; + +class JSApplicationInformationArray +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const Api::Application::ApplicationInformationArrayPtr &appinfoArray); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static Api::Application::ApplicationInformationArrayPtr + getApplicationInformationArray(JSContextRef context, JSValueRef value); + + private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; +} +} +} +#endif diff --git a/src/standards/Tizen/Application/JSApplicationServiceExtraData.cpp b/src/standards/Tizen/Application/JSApplicationServiceExtraData.cpp new file mode 100755 index 0000000..50423ce --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationServiceExtraData.cpp @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "JSApplicationServiceExtraData.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +using namespace Api::Application; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::CommonsJavaScript; + + +namespace { + const char* APPLICATION_SERVICE_EXTRA_DATA_KEY = "key"; + const char* APPLICATION_SERVICE_EXTRA_DATA_VALUE = "value"; +} + +JSClassRef JSApplicationServiceExtraData::m_classRef = NULL; + +JSClassDefinition JSApplicationServiceExtraData::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "ApplicationServiceExtraData", + NULL, + m_property, + m_functions, + initialize, + finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticValue JSApplicationServiceExtraData::m_property[] = { + { APPLICATION_SERVICE_EXTRA_DATA_KEY, getExtraDataKey, setExtraDataKey, kJSPropertyAttributeNone }, + { APPLICATION_SERVICE_EXTRA_DATA_VALUE, getExtraDataValue, setExtraDataValue, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSApplicationServiceExtraData::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSApplicationServiceExtraData::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSApplicationServiceExtraData::createJSObject(JSContextRef context, + const std::string &key, + const std::string &value) +{ + ApplicationServiceExtraDataPtr privateData = ApplicationServiceExtraDataPtr(new ApplicationServiceExtraData()); + + privateData->setKey(key); + privateData->setValue(value); + JSApplicationServiceExtraDataPriv *priv = new JSApplicationServiceExtraDataPriv(context, privateData); + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast(priv)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +void JSApplicationServiceExtraData::initialize(JSContextRef context, JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSApplicationServiceExtraData::finalize(JSObjectRef object) +{ + //delete (JSObjectGetPrivate(object)); +} + +bool JSApplicationServiceExtraData::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ApplicationServiceExtraDataPtr JSApplicationServiceExtraData::getPrivData(JSObjectRef object) +{ + LogDebug("entered"); + JSApplicationServiceExtraDataPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(Commons::NullPointerException, "Private object is null"); + } + ApplicationServiceExtraDataPtr result = priv->getObject(); + if (!result) { + ThrowMsg(Commons::NullPointerException, "Private object is null"); + } + return result; +} + +ApplicationServiceExtraDataPtr + JSApplicationServiceExtraData::getApplicationServiceExtraData(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(Commons::InvalidArgumentException); + } + JSApplicationServiceExtraDataPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(Commons::NullPointerException); + } + return priv->getObject(); +} + +JSValueRef JSApplicationServiceExtraData::getExtraDataKey(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CommonsJavaScript::Converter converter(context); + ApplicationServiceExtraDataPtr privateData = getPrivData(object); + return converter.toJSValueRef(privateData->getKey()); + } + Catch(Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSApplicationServiceExtraData::setExtraDataKey(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef key, + JSValueRef* exception) +{ + Try + { + ApplicationServiceExtraDataPtr privateData = getPrivData(object); + CommonsJavaScript::Converter converter(context); + privateData->setKey(converter.toString(key)); + return true; + } + Catch(Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSDOMExceptionFactory::TypeMismatchException.make(context, exception); + return false; +} + +JSValueRef JSApplicationServiceExtraData::getExtraDataValue(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + ApplicationServiceExtraDataPtr privateData = getPrivData(object); + return converter.toJSValueRef(privateData->getValue()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSApplicationServiceExtraData::setExtraDataValue(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ApplicationServiceExtraDataPtr privateData = getPrivData(object); + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + privateData->setValue(converter.toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSDOMExceptionFactory::TypeMismatchException.make(context, exception); + return false; +} + +} +} +} diff --git a/src/standards/Tizen/Application/JSApplicationServiceExtraData.h b/src/standards/Tizen/Application/JSApplicationServiceExtraData.h new file mode 100755 index 0000000..02f5688 --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationServiceExtraData.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_JS_APPLICATION_SERVICE_EXTRA_DATA_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_SERVICE_EXTRA_DATA_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject JSApplicationServiceExtraDataPriv; + +class JSApplicationServiceExtraData { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context, + const std::string &key, + const std::string &value); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static Api::Application::ApplicationServiceExtraDataPtr + getApplicationServiceExtraData(JSContextRef context, JSValueRef value); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static Api::Application::ApplicationServiceExtraDataPtr getPrivData(JSObjectRef object); + + static JSValueRef getExtraDataKey(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setExtraDataKey(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef key, + JSValueRef* exception); + + static JSValueRef getExtraDataValue(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setExtraDataValue(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + +}; + +} +} +} +#endif + diff --git a/src/standards/Tizen/Application/JSApplicationServiceExtraDataArray.cpp b/src/standards/Tizen/Application/JSApplicationServiceExtraDataArray.cpp new file mode 100755 index 0000000..d9d436c --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationServiceExtraDataArray.cpp @@ -0,0 +1,575 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "JSApplicationServiceExtraDataArray.h" +#include "ApplicationConverter.h" + + +namespace { +const char* FUNCTION_CONCAT = "concat"; +const char* FUNCTION_JOIN = "join"; +const char* FUNCTION_POP = "pop"; +const char* FUNCTION_PUSH = "push"; +const char* FUNCTION_REVERSE = "reverse"; +const char* FUNCTION_SHIFT = "shift"; +const char* FUNCTION_SLICE = "slice"; +const char* FUNCTION_SORT = "sort"; +const char* FUNCTION_SPLICE = "splice"; +const char* FUNCTION_TOSTRING = "toString"; +const char* FUNCTION_UNSHIFT = "unshift"; +const char* FUNCTION_VALUEOF = "valueOf"; +const char *ARRAY = "Array"; +const char *ATTRIBUTE_LENGTH = "length"; +} + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +using namespace Api::Application; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::CommonsJavaScript; + + +JSClassDefinition JSApplicationServiceExtraDataArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSApplicationServiceExtraDataArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSApplicationServiceExtraDataArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSApplicationServiceExtraDataArray::m_jsClassRef = JSClassCreate( + JSApplicationServiceExtraDataArray::getClassInfo()); + +JSValueRef JSApplicationServiceExtraDataArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + Try + { + JSApplicationServiceExtraDataArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(Commons::NullPointerException); + } + ApplicationServiceExtraDataArrayPtr privateDatas = priv->getObject(); + if (privateDatas) { + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + return converter->toJSValueRef(privateDatas->size()); + } + } + Catch(Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSApplicationServiceExtraDataArray::createArray(JSContextRef context, + const ApplicationServiceExtraDataArrayPtr &privateDatas) +{ + JSApplicationServiceExtraDataArrayPriv *priv = new JSApplicationServiceExtraDataArrayPriv(context, privateDatas); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSApplicationServiceExtraDataArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSApplicationServiceExtraDataArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +bool JSApplicationServiceExtraDataArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ApplicationServiceExtraDataArrayPtr + JSApplicationServiceExtraDataArray::getApplicationServiceExtraDataArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(Commons::InvalidArgumentException); + } + JSApplicationServiceExtraDataArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSApplicationServiceExtraDataArray::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("enter"); +} + +void JSApplicationServiceExtraDataArray::finalize(JSObjectRef object) +{ + LogDebug("enter"); + JSApplicationServiceExtraDataArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSApplicationServiceExtraDataArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + LogDebug("enter"); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSApplicationServiceExtraDataArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(Commons::NullPointerException); + } + ApplicationServiceExtraDataArrayPtr privateDatas = priv->getObject(); + if (index < privateDatas->size()) { + return true; + } + } + Catch(Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSApplicationServiceExtraDataArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSApplicationServiceExtraDataArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(Commons::NullPointerException); + } + ApplicationServiceExtraDataArrayPtr privateDatas = priv->getObject(); + if (index < privateDatas->size()) { + ApplicationServiceExtraDataPtr result = privateDatas->at(index); + if (result) { + return converter->toJSValueRef(result); + } + } + } + Catch(Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSApplicationServiceExtraDataArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("enter"); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); +// CommonsJavaScript::Converter converter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + ApplicationServiceExtraDataPtr privateData; + if (!JSValueIsUndefined(context, value)) { + privateData = converter->toApplicationServiceExtraData(value); + } + JSApplicationServiceExtraDataArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(Commons::NullPointerException); + } + ApplicationServiceExtraDataArrayPtr privateDatas = priv->getObject(); + if (!privateDatas) { + Throw(Commons::NullPointerException); + } + if (privateDatas->size() <= index) { + privateDatas->resize(index + 1); + } + (*privateDatas)[index] = privateData; + return true; + } + Catch(Commons::Exception) + { + LogError("error occured"); + JSDOMExceptionFactory::TypeMismatchException.make(context, exception); + } + return false; +} + +JSValueRef JSApplicationServiceExtraDataArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("enter"); + Try + { + ApplicationServiceExtraDataArrayPtr privateDatas = ApplicationServiceExtraDataArrayPtr(new ApplicationServiceExtraDataArray()); + JSApplicationServiceExtraDataArrayPriv *newPrivateObject = new JSApplicationServiceExtraDataArrayPriv(context, privateDatas); + JSValueRef result = JSObjectMake(context, getClassRef(), newPrivateObject); + + //copy current privateDatas + JSApplicationServiceExtraDataArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationServiceExtraDataArrayPtr currentApplicationServiceExtraDatas = priv->getObject(); + for (size_t i = 0; i < currentApplicationServiceExtraDatas->size(); ++i) { + privateDatas->push_back(currentApplicationServiceExtraDatas->at(i)); + } + + //copy submitted arrays + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(Commons::ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + privateDatas->push_back(converter->toApplicationServiceExtraData(att)); + } + } + return result; + } + Catch(Commons::Exception) + { + LogError("error occured"); + } + return JSDOMExceptionFactory::TypeMismatchException.make(context, exception); +} + +JSValueRef JSApplicationServiceExtraDataArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + JSApplicationServiceExtraDataArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationServiceExtraDataArrayPtr currentApplicationServiceExtraDatas = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentApplicationServiceExtraDatas->size(); ++i) { + if (i != 0) { + result += separator; + } + //FIXME : to be changed to support join + //result += currentApplicationServiceExtraDatas->at(i); + } + return converter->toJSValueRef(result); + } + Catch(Commons::Exception) + { + LogError("error occured"); + } + return JSDOMExceptionFactory::TypeMismatchException.make(context, exception); +} + +JSValueRef JSApplicationServiceExtraDataArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + JSApplicationServiceExtraDataArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationServiceExtraDataArrayPtr currentApplicationServiceExtraDatas = priv->getObject(); + if (currentApplicationServiceExtraDatas->size() > 0) { + ApplicationServiceExtraDataPtr result = currentApplicationServiceExtraDatas->at( + currentApplicationServiceExtraDatas->size() - 1); + currentApplicationServiceExtraDatas->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplicationServiceExtraDataArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + JSApplicationServiceExtraDataArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationServiceExtraDataArrayPtr currentApplicationServiceExtraDatas = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentApplicationServiceExtraDatas->push_back(converter->toApplicationServiceExtraData(arguments[i])); + } + return converter->toJSValueRef(currentApplicationServiceExtraDatas->size()); + } + Catch(Commons::Exception) + { + LogError("error occured"); + } + return JSDOMExceptionFactory::TypeMismatchException.make(context, exception); +} + +JSValueRef JSApplicationServiceExtraDataArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + JSApplicationServiceExtraDataArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationServiceExtraDataArrayPtr currentApplicationServiceExtraDatas = priv->getObject(); + std::reverse(currentApplicationServiceExtraDatas->begin(), currentApplicationServiceExtraDatas->end()); + return thisObject; + } + Catch(Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplicationServiceExtraDataArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + JSApplicationServiceExtraDataArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationServiceExtraDataArrayPtr currentApplicationServiceExtraDatas = priv->getObject(); + if (currentApplicationServiceExtraDatas->size() > 0) { + ApplicationServiceExtraDataPtr result = currentApplicationServiceExtraDatas->at(0); + currentApplicationServiceExtraDatas->erase(currentApplicationServiceExtraDatas->begin()); + return converter->toJSValueRef(result); + } + } + Catch(Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplicationServiceExtraDataArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + ApplicationServiceExtraDataArrayPtr privateDatas = ApplicationServiceExtraDataArrayPtr(new ApplicationServiceExtraDataArray()); + JSApplicationServiceExtraDataArrayPriv *newPrivateObject = new JSApplicationServiceExtraDataArrayPriv( + context, + privateDatas); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current privateDatas + JSApplicationServiceExtraDataArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationServiceExtraDataArrayPtr currentApplicationServiceExtraDatas = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentApplicationServiceExtraDatas->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentApplicationServiceExtraDatas->size()) { + last = currentApplicationServiceExtraDatas->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + privateDatas->push_back(currentApplicationServiceExtraDatas->at(i)); + } + + return result; + } + Catch(Commons::Exception) + { + LogError("error occured"); + } + return JSDOMExceptionFactory::TypeMismatchException.make(context, exception); +} + +JSValueRef JSApplicationServiceExtraDataArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + //ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + JSApplicationServiceExtraDataArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ApplicationServiceExtraDataArrayPtr currentApplicationServiceExtraDatas = priv->getObject(); + std::sort(currentApplicationServiceExtraDatas->begin(), currentApplicationServiceExtraDatas->end()); + return thisObject; + } + Catch(Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplicationServiceExtraDataArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplicationServiceExtraDataArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSApplicationServiceExtraDataArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplicationServiceExtraDataArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} +} +} +} diff --git a/src/standards/Tizen/Application/JSApplicationServiceExtraDataArray.h b/src/standards/Tizen/Application/JSApplicationServiceExtraDataArray.h new file mode 100755 index 0000000..6141fb0 --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationServiceExtraDataArray.h @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_JS_APPLICATION_SERVICE_EXTRA_DATA_ARRAY_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_SERVICE_EXTRA_DATA_ARRAY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSApplicationServiceExtraDataArrayPriv; + +class JSApplicationServiceExtraDataArray +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const Api::Application::ApplicationServiceExtraDataArrayPtr &extraDataArray); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static Api::Application::ApplicationServiceExtraDataArrayPtr + getApplicationServiceExtraDataArray(JSContextRef context, JSValueRef value); + + private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; +} +} +} +#endif diff --git a/src/standards/Tizen/Application/JSApplicationServiceReply.cpp b/src/standards/Tizen/Application/JSApplicationServiceReply.cpp new file mode 100755 index 0000000..4e488c1 --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationServiceReply.cpp @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include "JSApplicationServiceReply.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace Api::Application; + +namespace { +const char* APPLICATION_SERVICE_REPLY_SUCCESS = "isSucceed"; +const char* APPLICATION_SERVICE_EXTRADATA = "extraData"; + + +} //private namespace + +JSClassRef JSApplicationServiceReply::m_jsClassRef = NULL; + +JSClassDefinition JSApplicationServiceReply::m_classInfo = { + 0, + kJSClassAttributeNone, + "ApplicationServiceReply", + 0, + m_property, + 0, + initialize, + finalize, + NULL, //HasProperty, + NULL, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, + NULL, //ConvertToType +}; + +JSStaticValue JSApplicationServiceReply::m_property[] = { + { APPLICATION_SERVICE_REPLY_SUCCESS, getIsSucceed, NULL, kJSPropertyAttributeReadOnly }, + { APPLICATION_SERVICE_EXTRADATA, getExtraData, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassDefinition* JSApplicationServiceReply::getClassInfo() +{ + return &m_classInfo; +} + +const JSClassRef JSApplicationServiceReply::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +JSObjectRef JSApplicationServiceReply::createJSObject(JSContextRef context, + const ApplicationServiceReplyPtr &appsvc) +{ + ApplicationServiceReplyPtr privateData(new ApplicationServiceReply()); + JSApplicationServiceReplyPriv *priv = new JSApplicationServiceReplyPriv(context, privateData); + + if (!priv) { + ThrowMsg(Commons::NullPointerException, "Can not new an object"); + } + return JSObjectMake(context, getClassRef(), priv); +} + +ApplicationServiceReplyPtr JSApplicationServiceReply::getApplicationServiceReply(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(Commons::InvalidArgumentException); + } + JSApplicationServiceReplyPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(Commons::NullPointerException); + } + return priv->getObject(); +} + +ApplicationServiceReplyPtr JSApplicationServiceReply::getPrivateData(JSObjectRef object) +{ + JSApplicationServiceReplyPriv* priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(Commons::NullPointerException); + } + return priv->getObject(); +} + + + +void JSApplicationServiceReply::initialize(JSContextRef context,JSObjectRef object) +{ + LogDebug("Entered. Nothing to do."); +} + +void JSApplicationServiceReply::finalize(JSObjectRef object) +{ + LogDebug("Entered"); + JSApplicationServiceReplyPriv* priv = + static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting ApplicationServiceReply object"); + delete priv; +} + +bool JSApplicationServiceReply::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +JSValueRef JSApplicationServiceReply::getIsSucceed(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + JSApplicationServiceReplyPriv *priv = + static_cast(JSObjectGetPrivate(object)); + assert(priv && "Private object not set."); + + Try { + ApplicationServiceReplyPtr appsvc = priv->getObject(); + CommonsJavaScript::Converter converter(context); + + if (JSStringIsEqualToUTF8CString(propertyName,APPLICATION_SERVICE_REPLY_SUCCESS)) { + LogDebug( + "JSApplicationServiceReply::getProperty ::success "); + + bool isSucceed = appsvc->getIsSucceed(); + return converter.toJSValueRef(isSucceed); + } + + } + Catch(Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSDOMExceptionFactory::UnknownException.make(context, exception); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSApplicationServiceReply::getExtraData(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + JSApplicationServiceReplyPriv *priv = + static_cast(JSObjectGetPrivate(object)); + assert(priv && "Private object not set."); + + Try { + ApplicationServiceReplyPtr appsvc = priv->getObject(); + CommonsJavaScript::Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName,APPLICATION_SERVICE_EXTRADATA)) { + LogDebug( + "JSApplicationServiceReply::getProperty ::extraData "); + + JSObjectRef result = JSApplicationServiceExtraDataArray::createArray(context, appsvc->getExtraDataArray()); + + return result; + } + } + Catch(Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSDOMExceptionFactory::UnknownException.make(context, exception); + } + return JSValueMakeUndefined(context); +} + +bool JSApplicationServiceReply::hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} +} // +} //TizenApis +} diff --git a/src/standards/Tizen/Application/JSApplicationServiceReply.h b/src/standards/Tizen/Application/JSApplicationServiceReply.h new file mode 100755 index 0000000..6e6dc72 --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationServiceReply.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_JS_APPLICATION_SERVICE_REPLY_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_SERVICE_REPLY_H_ + +#include +#include +#include +#include "JSApplicationServiceExtraDataArray.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSApplicationServiceReplyPriv; + +class JSApplicationServiceReply { +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + /** + * create an JSObject for callback function(onAnswerReceived). + */ + static JSObjectRef createJSObject(JSContextRef context, + const Api::Application::ApplicationServiceReplyPtr &appsvc); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static Api::Application::ApplicationServiceReplyPtr getApplicationServiceReply(JSContextRef context, JSValueRef value); + /** + * return private data + */ + static Api::Application::ApplicationServiceReplyPtr getPrivateData(JSObjectRef object); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a success property's value. + */ + static JSValueRef getIsSucceed(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * The callback invoked when getting a extraData property's value. + */ + static JSValueRef getExtraData(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + +}; + +} +} +} +#endif diff --git a/src/standards/Tizen/Application/JSApplicationServiceRequest.cpp b/src/standards/Tizen/Application/JSApplicationServiceRequest.cpp new file mode 100755 index 0000000..3d519d0 --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationServiceRequest.cpp @@ -0,0 +1,213 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include "JSApplicationServiceRequest.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::CommonsJavaScript; + +using namespace Api::Application; + +namespace { +const char* APPLICATION_SERVICE_OPERATION = "operation"; +const char* APPLICATION_SERVICE_URI = "uri"; +const char* APPLICATION_SERVICE_MIME = "mime"; +const char* APPLICATION_SERVICE_PACKAGE = "package"; +const char* APPLICATION_SERVICE_EXTRADATA = "extraData"; + + +} //private namespace + +JSClassRef JSApplicationServiceRequest::m_jsClassRef = NULL; + +JSClassDefinition JSApplicationServiceRequest::m_classInfo = { + 0, + kJSClassAttributeNone, + "ApplicationServiceRequest", + 0, + m_property, + 0, + initialize, + finalize, + NULL, //HasProperty, + getProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, + NULL, //ConvertToType +}; + +JSStaticValue JSApplicationServiceRequest::m_property[] = { + { APPLICATION_SERVICE_OPERATION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { APPLICATION_SERVICE_URI, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { APPLICATION_SERVICE_MIME, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { APPLICATION_SERVICE_PACKAGE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { APPLICATION_SERVICE_EXTRADATA, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassDefinition* JSApplicationServiceRequest::getClassInfo() +{ + return &m_classInfo; +} + +const JSClassRef JSApplicationServiceRequest::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +//JSClassRef JSApplicationServiceRequest::m_jsClassRef = JSClassCreate( +// JSApplicationServiceRequest::getClassInfo()); + +JSObjectRef JSApplicationServiceRequest::createJSObject(JSContextRef context, + const ApplicationServiceRequestPtr &appsvc) +{ + ApplicationServiceRequestPtr privateData(new ApplicationServiceRequest()); + JSApplicationServiceRequestPriv *priv = new JSApplicationServiceRequestPriv(context, privateData); + + if (!priv) { + ThrowMsg(Commons::NullPointerException, "Can not new an object"); + } + return JSObjectMake(context, getClassRef(), priv); +} + +ApplicationServiceRequestPtr JSApplicationServiceRequest::getApplicationServiceRequest(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(Commons::InvalidArgumentException); + } + JSApplicationServiceRequestPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(Commons::NullPointerException); + } + return priv->getObject(); +} + +ApplicationServiceRequestPtr JSApplicationServiceRequest::getPrivateData(JSObjectRef object) +{ + JSApplicationServiceRequestPriv* priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(Commons::NullPointerException); + } + return priv->getObject(); +} + + + +void JSApplicationServiceRequest::initialize(JSContextRef context,JSObjectRef object) +{ + LogDebug("Entered. Nothing to do."); +} + +void JSApplicationServiceRequest::finalize(JSObjectRef object) +{ + LogDebug("Entered"); + JSApplicationServiceRequestPriv* priv = + static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting ApplicationServiceRequest object"); + delete priv; +} + +bool JSApplicationServiceRequest::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +JSValueRef JSApplicationServiceRequest::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + JSApplicationServiceRequestPriv *priv = + static_cast(JSObjectGetPrivate(object)); + assert(priv && "Private object not set."); + + Try { + ApplicationServiceRequestPtr appsvc = priv->getObject(); + CommonsJavaScript::Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, APPLICATION_SERVICE_OPERATION)) { + LogDebug( + "JSApplicationServiceRequest::getProperty::operation " << + appsvc->getOperation()); + return convert.toJSValueRef(appsvc->getOperation()); + }else if (JSStringIsEqualToUTF8CString(propertyName, + APPLICATION_SERVICE_URI)) { + LogDebug( + "JSApplicationServiceRequest::getProperty ::uri " << + appsvc->getUri()); + return convert.toJSValueRef(appsvc->getUri()); + }else if (JSStringIsEqualToUTF8CString(propertyName, + APPLICATION_SERVICE_MIME)) { + LogDebug( + "JSApplicationServiceRequest::getProperty ::mime " << + appsvc->getMime()); + return convert.toJSValueRef(appsvc->getMime()); + }else if (JSStringIsEqualToUTF8CString(propertyName, + APPLICATION_SERVICE_PACKAGE)) { + LogDebug( + "JSApplicationServiceRequest::getProperty ::package " << + appsvc->getPackage()); + return convert.toJSValueRef(appsvc->getPackage()); + } + else if (JSStringIsEqualToUTF8CString(propertyName, + APPLICATION_SERVICE_EXTRADATA)) { + LogDebug( + "JSApplicationServiceRequest::getProperty ::extraData "); + JSObjectRef result = JSApplicationServiceExtraDataArray::createArray(context, appsvc->getExtraDataArray()); + + return result; + } + + } + Catch(Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSDOMExceptionFactory::UnknownException.make(context, exception); + } + return JSValueMakeUndefined(context); +} + +bool JSApplicationServiceRequest::hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} +} // +} //TizenApis +} diff --git a/src/standards/Tizen/Application/JSApplicationServiceRequest.h b/src/standards/Tizen/Application/JSApplicationServiceRequest.h new file mode 100755 index 0000000..1c14755 --- /dev/null +++ b/src/standards/Tizen/Application/JSApplicationServiceRequest.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_JS_APPLICATION_SERVICE_REQUEST_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_SERVICE_REQUEST_H_ + +#include +#include +#include +#include "JSApplicationServiceExtraDataArray.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSApplicationServiceRequestPriv; + +class JSApplicationServiceRequest { +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + /** + * create an JSObject for callback function(onAnswerReceived). + */ + static JSObjectRef createJSObject(JSContextRef context, + const Api::Application::ApplicationServiceRequestPtr &appsvc); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static Api::Application::ApplicationServiceRequestPtr getApplicationServiceRequest(JSContextRef context, JSValueRef value); + /** + * return private data + */ + static Api::Application::ApplicationServiceRequestPtr getPrivateData(JSObjectRef object); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + +}; + +} // +} //TizenApis +} +#endif diff --git a/src/standards/Tizen/Application/LaunchServicePrivateData.cpp b/src/standards/Tizen/Application/LaunchServicePrivateData.cpp new file mode 100755 index 0000000..518fd51 --- /dev/null +++ b/src/standards/Tizen/Application/LaunchServicePrivateData.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "LaunchServicePrivateData.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { +LaunchServicePrivateData::LaunchServicePrivateData( + const JSCallbackManagerPtr& callbackManager, + const JSCallbackManagerPtr& replyCallbackManager, + const JSCallbackManagerPtr& replyCancelCallbackManager): + m_callbackManager(callbackManager), + m_replyCallbackManager(replyCallbackManager), + m_replyCancelCallbackManager(replyCancelCallbackManager) +{ +} + +JSCallbackManagerPtr LaunchServicePrivateData::getCallbackManager() const +{ + return m_callbackManager; +} + +JSCallbackManagerPtr LaunchServicePrivateData::getReplyCallbackManager() +const +{ + return m_replyCallbackManager; +} + +JSCallbackManagerPtr LaunchServicePrivateData::getReplyCancelCallbackManager() +const +{ + return m_replyCancelCallbackManager; +} + +} +} +} diff --git a/src/standards/Tizen/Application/LaunchServicePrivateData.h b/src/standards/Tizen/Application/LaunchServicePrivateData.h new file mode 100755 index 0000000..a633bf7 --- /dev/null +++ b/src/standards/Tizen/Application/LaunchServicePrivateData.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_TIZEN_LAUNCH_SERVICE_PRIVATE_DATA_H_ +#define TIZENAPIS_TIZEN_LAUNCH_SERVICE_PRIVATE_DATA_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +using namespace WrtDeviceApis::CommonsJavaScript; + +class LaunchServicePrivateData : public WrtDeviceApis::Commons::IEventPrivateData +{ + public: + LaunchServicePrivateData(const JSCallbackManagerPtr& callbackManager, + const JSCallbackManagerPtr& replayCallbackManager, const JSCallbackManagerPtr& replayCancelCallbackManager); + + JSCallbackManagerPtr getCallbackManager() const; + JSCallbackManagerPtr getReplyCallbackManager() const; + JSCallbackManagerPtr getReplyCancelCallbackManager() const; + + private: + JSCallbackManagerPtr m_callbackManager; + JSCallbackManagerPtr m_replyCallbackManager; + JSCallbackManagerPtr m_replyCancelCallbackManager; +}; + +typedef DPL::SharedPtr LaunchServicePrivateDataPtr; +} +} +} +#endif diff --git a/src/standards/Tizen/Application/config.xml b/src/standards/Tizen/Application/config.xml new file mode 100755 index 0000000..45646ff --- /dev/null +++ b/src/standards/Tizen/Application/config.xml @@ -0,0 +1,26 @@ + + + + libwrt-plugins-tizen-1.0-application.so + application.install.uri + SAMSUNG plugin group + SAMSUNG certificate authority + AAAABBBBCCCCDDDEEEE0000 + + + + http://tizen.org/api/application + application.manager + application.service + + + + http://tizen.org/api/application.manager + application.manager + + + http://tizen.org/api/application.service + application.service + + + diff --git a/src/standards/Tizen/Application/plugin_config.cpp b/src/standards/Tizen/Application/plugin_config.cpp new file mode 100755 index 0000000..2b1dbb9 --- /dev/null +++ b/src/standards/Tizen/Application/plugin_config.cpp @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include + +#include "plugin_config.h" + +#define APPLICATION_FEATURE_API "http://tizen.org/api/application" +#define APPLICATION_FEATURE_API_MANAGER "http://tizen.org/api/application.manager" +#define APPLICATION_FEATURE_API_SERVICE "http://tizen.org/api/application.service" + +#define APPLICATION_DEVICE_CAP_MANAGER "application.manager" +#define APPLICATION_DEVICE_CAP_SERVICE "application.service" + +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +static FunctionMapping createApplicationFunctions(); + +static FunctionMapping ApplicationFunctions = + createApplicationFunctions(); + +DEFINE_FUNCTION_GETTER(Application, ApplicationFunctions); + +static FunctionMapping createApplicationFunctions() +{ + /** + * Device capabilities + */ + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_APPLICATION_MANAGER, APPLICATION_DEVICE_CAP_MANAGER); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_APPLICATION_SERVICE, APPLICATION_DEVICE_CAP_SERVICE); + + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_APPLICATION_MANAGER); + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_APPLICATION_SERVICE); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_APPLICATION_MANAGER, DEVICE_CAP_APPLICATION_MANAGER); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_APPLICATION_SERVICE, DEVICE_CAP_APPLICATION_SERVICE); + + /** + * Api Features + */ + ACE_CREATE_FEATURE(FEATURE_APPLICATION, APPLICATION_FEATURE_API); + ACE_CREATE_FEATURE(FEATURE_APPLICATION_MANAGER, APPLICATION_FEATURE_API_MANAGER); + ACE_CREATE_FEATURE(FEATURE_APPLICATION_SERVICE, APPLICATION_FEATURE_API_SERVICE); + + ACE_CREATE_FEATURE_LIST(APPLICATION_FEATURES_APPLICATION_MANAGER); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_MANAGER, FEATURE_APPLICATION); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_MANAGER, FEATURE_APPLICATION_MANAGER); + + ACE_CREATE_FEATURE_LIST(APPLICATION_FEATURES_APPLICATION_SERVICE); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_SERVICE, FEATURE_APPLICATION); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_SERVICE, FEATURE_APPLICATION_SERVICE); + + ACE_CREATE_FEATURE_LIST(APPLICATION_FEATURES); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES, FEATURE_APPLICATION); + + ACE_CREATE_FEATURE_LIST(APPLICATION_FEATURES_MANAGER); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_MANAGER, FEATURE_APPLICATION_MANAGER); + + ACE_CREATE_FEATURE_LIST(APPLICATION_FEATURES_SERVICE); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_SERVICE, FEATURE_APPLICATION_SERVICE); + + + /** + * Functions + */ + FunctionMapping applicationMapping; + + // listInstalledApplications + AceFunction listInstalledApplicationsFunc = ACE_CREATE_FUNCTION( + FUNCTION_LIST_INSTALLED_APPLICATIONS, + APPLICATION_FUNCTION_API_LIST_INSTALLED_APPLICATIONS, + APPLICATION_FEATURES_APPLICATION_MANAGER, + DEVICE_LIST_APPLICATION_MANAGER); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_LIST_INSTALLED_APPLICATIONS, + listInstalledApplicationsFunc)); + + // listRunningApplications + AceFunction listRunningApplicationsFunc = ACE_CREATE_FUNCTION( + FUNCTION_LIST_RUNNING_APPLICATIONS, + APPLICATION_FUNCTION_API_LIST_RUNNING_APPLICATIONS, + APPLICATION_FEATURES_APPLICATION_MANAGER, + DEVICE_LIST_APPLICATION_MANAGER); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_LIST_RUNNING_APPLICATIONS, + listRunningApplicationsFunc)); + + // getApplicationInformation + AceFunction getApplicationInformationFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_APPLICATION_INFORMATION, + APPLICATION_FUNCTION_API_GET_APPLICATION_INFORMATION, + APPLICATION_FEATURES_APPLICATION_MANAGER, + DEVICE_LIST_APPLICATION_MANAGER); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_GET_APPLICATION_INFORMATION, + getApplicationInformationFunc)); + + // addApplicationListChangeListener + AceFunction addApplicationListChangeListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_ADD_APPLICATION_LIST_CHANGE_LISTENER, + APPLICATION_FUNCTION_API_ADD_APPLICATION_LIST_CHANGE_LISTENER, + APPLICATION_FEATURES_APPLICATION_MANAGER, + DEVICE_LIST_APPLICATION_MANAGER); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_ADD_APPLICATION_LIST_CHANGE_LISTENER, + addApplicationListChangeListenerFunc)); + + // unsetApplicaitonListChangeListener + AceFunction unsetApplicaitonListChangeListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_REMOVE_APPLICATOIN_LIST_CHANGE_LISTENER, + APPLICATION_FUNCTION_API_REMOVE_APPLICATION_LIST_CHANGE_LISTENER, + APPLICATION_FEATURES_APPLICATION_MANAGER, + DEVICE_LIST_APPLICATION_MANAGER); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_REMOVE_APPLICATION_LIST_CHANGE_LISTENER, + unsetApplicaitonListChangeListenerFunc)); + + // launchService + AceFunction launchServiceFunc = ACE_CREATE_FUNCTION( + FUNCTION_LAUNCH_SERVICE, + APPLICATION_FUNCTION_API_LAUNCH_SERVICE, + APPLICATION_FEATURES_APPLICATION_SERVICE, + DEVICE_LIST_APPLICATION_SERVICE); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_LAUNCH_SERVICE, + launchServiceFunc)); + + + return applicationMapping; +} + +} +} +} diff --git a/src/standards/Tizen/Application/plugin_config.h b/src/standards/Tizen/Application/plugin_config.h new file mode 100755 index 0000000..40a09d8 --- /dev/null +++ b/src/standards/Tizen/Application/plugin_config.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _APPLICATOIN_PLUGIN_CONFIG_H_ +#define _APPLICATOIN_PLUGIN_CONFIG_H_ + +#include +#include + +#define APPLICATION_FUNCTION_API_LIST_INSTALLED_APPLICATIONS "listInstalledApplications" +#define APPLICATION_FUNCTION_API_LIST_RUNNING_APPLICATIONS "listRunningApplications" +#define APPLICATION_FUNCTION_API_GET_APPLICATION_INFORMATION "getApplicationInformation" +#define APPLICATION_FUNCTION_API_ADD_APPLICATION_LIST_CHANGE_LISTENER "addApplicationListChangeListener" +#define APPLICATION_FUNCTION_API_REMOVE_APPLICATION_LIST_CHANGE_LISTENER "removeApplicationListChangeListener" +#define APPLICATION_FUNCTION_API_LAUNCH_SERVICE "launchService" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Application { + +DECLARE_FUNCTION_GETTER(Application); + +#define APPLICATION_CHECK_ACCESS(globalContext, functionName) \ + aceCheckAccess >( \ + globalContext, \ + getApplicationFunctionData, \ + functionName) +} +} +} +#endif + diff --git a/src/standards/Tizen/Application/plugin_initializer.cpp b/src/standards/Tizen/Application/plugin_initializer.cpp new file mode 100755 index 0000000..81b9758 --- /dev/null +++ b/src/standards/Tizen/Application/plugin_initializer.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include "JSApplication.h" + +void on_widget_start_callback(int widgetId, JavaScriptContext context, const engine_interface_t *interface) { + LogDebug("[Tizen1_0\\Application] on_widget_start_callback ("< +#include +#include +#include +#include +#include +#include +#include +#include "BluetoothAdapterListener.h" +#include "JSBluetoothDevice.h" +#include +#include +#include "BluetoothMultiCallback.h" +#include "JSBluetoothSocket.h" +#include "BluetoothConverter.h" +#include +#include + +using namespace TizenApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { + + +BluetoothAdapterListener::~BluetoothAdapterListener() +{ + LogDebug("entered"); +} + +BluetoothAdapterListener::BluetoothAdapterListener() : + EventBTCreateDestroyBondingAnswerReceiver(ThreadEnum::NULL_THREAD), + EventBTGetKnownDevicesAnswerReceiver(ThreadEnum::NULL_THREAD), + EventBTGetDeviceAnswerReceiver(ThreadEnum::NULL_THREAD), + EventBTSetPoweredAnswerReceiver(ThreadEnum::NULL_THREAD), + EventBTSetVisibleAnswerReceiver(ThreadEnum::NULL_THREAD), + EventBTOnDiscoveryDevicesListener(ThreadEnum::NULL_THREAD), + EventBTRegisterRFCOMMListener(ThreadEnum::NULL_THREAD), + EventBTUnregisterRFCOMMServiceAnswerReceiver(ThreadEnum::NULL_THREAD), + EventBTStopDiscoveryAnswerReceiver(ThreadEnum::NULL_THREAD), + EventBTSetNameAnswerReceiver(ThreadEnum::NULL_THREAD) +{ + LogDebug("entered"); +} + + +BluetoothAdapterListener& BluetoothAdapterListener::getInstance() +{ + static BluetoothAdapterListener instance; + return instance; + +} + +void BluetoothAdapterListener::MakeErrorJSCallBack(JSCallbackManagerPtr cbm, JSContextRef globalContext, unsigned short error) +{ + LogDebug("Enter"); + JSValueRef err = 0; + + switch (error) + { + case ExceptionCodes::SecurityException: + err = JSTizenExceptionFactory::makeErrorObject(globalContext, + JSTizenException::PERMISSION_DENIED_ERROR, "permission denied error"); + + break; + case ExceptionCodes::UnsupportedException: + err = JSTizenExceptionFactory::makeErrorObject(globalContext, + JSTizenException::NOT_SUPPORTED_ERROR, "unsupport error"); + break; + case ExceptionCodes::UnknownException: + default: + err = JSTizenExceptionFactory::makeErrorObject(globalContext, + JSTizenException::UNKNOWN_ERROR, "unknown error"); + break; + } + cbm->callOnError(err); +} + +void BluetoothAdapterListener::OnAnswerReceived(const EventBTCreateDestroyBondingPtr& event) +{ + LogDebug("Enter - EventBTCreateDestroyBondingPtr"); + JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast (event->getPrivateData()); + JSContextRef l_globalContext = callbackManager->getContext(); + + if (event->getExceptionCode() == ExceptionCodes::None) + { + if (event->isCreateBonding()) + { + BluetoothDeviceData device = event->getDevice(); + JSObjectRef deviceObject = JSBluetoothDevice::createJSObject(l_globalContext, device); + callbackManager->callOnSuccess(deviceObject); + } + else + { + callbackManager->callOnSuccess(); + } + } + else + { + MakeErrorJSCallBack(callbackManager, l_globalContext, event->getExceptionCode()); + } + +} + +void BluetoothAdapterListener::OnAnswerReceived(const EventBTGetKnownDevicesPtr& event) +{ + LogDebug("Enter - EventBTGetKnownDevicesPtr"); + JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast (event->getPrivateData()); + JSContextRef l_globalContext = callbackManager->getContext(); + + if (event->getExceptionCode() == ExceptionCodes::None) + { + std::vector devices = event->getDevices(); + BluetoothConverter converter(l_globalContext); + JSObjectRef result = converter.toBluetoothDevices(devices); + callbackManager->callOnSuccess(result); + } + else + { + MakeErrorJSCallBack(callbackManager, l_globalContext, event->getExceptionCode()); + } + + + } + + +void BluetoothAdapterListener::OnAnswerReceived(const EventBTSetPoweredPtr& event) +{ + LogDebug("Enter - EventBTSetPoweredPtr"); + JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast (event->getPrivateData()); + JSContextRef l_globalContext = callbackManager->getContext(); + + + if (event->getExceptionCode() == ExceptionCodes::None) + { + callbackManager->callOnSuccess(); + } + else + { + MakeErrorJSCallBack(callbackManager, l_globalContext, event->getExceptionCode()); + } +} + +void BluetoothAdapterListener::OnAnswerReceived(const EventBTGetDevicePtr& event) +{ + LogDebug("Enter - EventBTGetDevicePtr"); + JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast (event->getPrivateData()); + JSContextRef l_globalContext = callbackManager->getContext(); + + if (event->getExceptionCode() == ExceptionCodes::None) + { + BluetoothDeviceData device = event->getDevice(); + LogDebug("Enter" << device.name << " " << device.address << "major: " << device.btClass.major << "minor: " << device.btClass.minor); + JSObjectRef adapterObject = JSBluetoothDevice::createJSObject(callbackManager->getContext(), device); + callbackManager->callOnSuccess(adapterObject); + } + else + { + MakeErrorJSCallBack(callbackManager, l_globalContext, event->getExceptionCode()); + } + +} + + +void BluetoothAdapterListener::OnAnswerReceived(const EventBTSetVisiblePtr& event) +{ + LogDebug("Enter - EventBTSetVisiblePtr"); + JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast (event->getPrivateData()); + JSContextRef l_globalContext = callbackManager->getContext(); + + if (event->getExceptionCode() == ExceptionCodes::None) + { + callbackManager->callOnSuccess(); + } + else + { + MakeErrorJSCallBack(callbackManager, l_globalContext, event->getExceptionCode()); + } +} + +void BluetoothAdapterListener::OnAnswerReceived(const EventBTUnregisterRFCOMMServicePtr& event) +{ + LogDebug("Enter - EventBTUnregisterRFCOMMServicePtr"); + JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast (event->getPrivateData()); + JSContextRef l_globalContext = callbackManager->getContext(); + + if (event->getExceptionCode() == ExceptionCodes::None) + { + callbackManager->callOnSuccess(); + } + else + { + MakeErrorJSCallBack(callbackManager, l_globalContext, event->getExceptionCode()); + } +} + + +void BluetoothAdapterListener::onAnswerReceived(const EventBTOnDiscoveryDevicesPtr& event) +{ + LogDebug("Enter"); + + EventBTOnDiscoveryDevicesPrivateDataPtr multiCallbacks = + DPL::DynamicPointerCast(event->getPrivateData()); + JSCallbackManagerPtr defaultCbm = multiCallbacks->getOnSuccess(); + std::vector devices; + + assert(multiCallbacks != NULL); + assert(defaultCbm != NULL); + assert(multiCallbacks->getOnFound() != NULL); + assert(multiCallbacks->getOnFinished() != NULL); + + if (event->getExceptionCode() == ExceptionCodes::None) + { + switch(event->getDiscoveryState()) + { + case EventBTOnDiscoveryDevices::STARTED: + multiCallbacks->getOnSuccess()->callOnSuccess(); + break; + case EventBTOnDiscoveryDevices::DISCOVERYING: + { + JSObjectRef adapterObject; + devices = event->getDevices(); + defaultCbm = multiCallbacks->getOnFound(); + adapterObject = JSBluetoothDevice::createJSObject(defaultCbm->getContext(), devices[0]); + defaultCbm->callOnSuccess(adapterObject); + } + break; + + case EventBTOnDiscoveryDevices::FINISHED: + { + devices = event->getDevices(); + defaultCbm = multiCallbacks->getOnFinished(); + + BluetoothConverter converter(defaultCbm->getContext()); + JSObjectRef result = converter.toBluetoothDevices(devices); + defaultCbm->callOnSuccess(result); + } + break; + default: + MakeErrorJSCallBack(defaultCbm, defaultCbm->getContext(), event->getExceptionCode()); + break; + + } + } + else + { + MakeErrorJSCallBack(defaultCbm, defaultCbm->getContext(), event->getExceptionCode()); + } +} + +void BluetoothAdapterListener::onAnswerReceived(const EventBTRegisterRFCOMMPtr& event) +{ + LogDebug("Enter"); + + BluetoothRegisterServiceSuccessCallbackPrivateDataPtr multiCallbacks = + DPL::DynamicPointerCast(event->getPrivateData()); + + BluetoothSocketData socketData; + JSObjectRef adapterObject; + assert(multiCallbacks != NULL); + assert(multiCallbacks->getOnSuccess() != NULL); + assert(multiCallbacks->getOnConnected() != NULL); + assert(multiCallbacks->getOnSuccess()->getContext() != NULL); + + if (event->getExceptionCode() == ExceptionCodes::None) + { + switch(event->getConnectionState()) + { + case EventBTRegisterRFCOMM::REGISTER_SUCCESS: + multiCallbacks->getOnSuccess()->callOnSuccess(); + break; + case EventBTRegisterRFCOMM::REGISTER_CONNECTED: + socketData = event->getSocketData(); + adapterObject = JSBluetoothSocket::createJSObject(multiCallbacks->getOnSuccess()->getContext(), socketData); + multiCallbacks->getOnConnected()->callOnSuccess(adapterObject); + break; + case EventBTRegisterRFCOMM::REGISTER_DISCONNECTED: + default: + MakeErrorJSCallBack(multiCallbacks->getOnSuccess(), + multiCallbacks->getOnSuccess()->getContext(), event->getExceptionCode()); + break; + } + + } + else + { + MakeErrorJSCallBack(multiCallbacks->getOnSuccess(), + multiCallbacks->getOnSuccess()->getContext(), event->getExceptionCode()); + } + +} + +void BluetoothAdapterListener::OnAnswerReceived(const EventBTStopDiscoveryPtr& event) +{ + LogDebug("Enter - EventBTStopDiscoveryPtr"); + JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast (event->getPrivateData()); + JSContextRef l_globalContext = callbackManager->getContext(); + + if (event->getExceptionCode() == ExceptionCodes::None) + { + callbackManager->callOnSuccess(); + } + else + { + MakeErrorJSCallBack(callbackManager, l_globalContext, event->getExceptionCode()); + } +} + +void BluetoothAdapterListener::OnAnswerReceived(const EventBTSetNamePtr& event) +{ + LogDebug("Enter - EventBTStopDiscoveryPtr"); + JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast (event->getPrivateData()); + JSContextRef l_globalContext = callbackManager->getContext(); + + if (event->getExceptionCode() == ExceptionCodes::None) + { + callbackManager->callOnSuccess(); + } + else + { + MakeErrorJSCallBack(callbackManager, l_globalContext, event->getExceptionCode()); + } +} +} +} diff --git a/src/standards/Tizen/Bluetooth/BluetoothAdapterListener.h b/src/standards/Tizen/Bluetooth/BluetoothAdapterListener.h new file mode 100755 index 0000000..9599220 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/BluetoothAdapterListener.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_BLUETOOTH_ADAPTER_LISTENER_H_ +#define TIZENAPIS_TIZEN_BLUETOOTH_ADAPTER_LISTENER_H_ + +#include +#include +#include +#include +#include + + +using namespace TizenApis::Api; +using namespace TizenApis::Api::Bluetooth; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0{ + + +typedef EventAnswerReceiver EventBTCreateDestroyBondingAnswerReceiver; +typedef EventAnswerReceiver EventBTGetKnownDevicesAnswerReceiver; +typedef EventAnswerReceiver EventBTGetDeviceAnswerReceiver; +typedef EventAnswerReceiver EventBTSetPoweredAnswerReceiver; +typedef EventAnswerReceiver EventBTSetVisibleAnswerReceiver; +typedef EventListener EventBTOnDiscoveryDevicesListener; +typedef EventListener EventBTRegisterRFCOMMListener; +typedef EventAnswerReceiver EventBTUnregisterRFCOMMServiceAnswerReceiver; +typedef EventAnswerReceiver EventBTStopDiscoveryAnswerReceiver; +typedef EventAnswerReceiver EventBTSetNameAnswerReceiver; + + + +class BluetoothAdapterListener : + public EventBTCreateDestroyBondingAnswerReceiver, + public EventBTGetKnownDevicesAnswerReceiver, + public EventBTGetDeviceAnswerReceiver, + public EventBTSetPoweredAnswerReceiver, + public EventBTSetVisibleAnswerReceiver, + public EventBTOnDiscoveryDevicesListener, + public EventBTRegisterRFCOMMListener, + public EventBTUnregisterRFCOMMServiceAnswerReceiver, + public EventBTStopDiscoveryAnswerReceiver, + public EventBTSetNameAnswerReceiver +{ + +private: + BluetoothAdapterListener(); + void MakeErrorJSCallBack(JSCallbackManagerPtr cbm, JSContextRef globalContext, unsigned short error); +public: + static BluetoothAdapterListener& getInstance(); + virtual void onAnswerReceived(const EventBTOnDiscoveryDevicesPtr& event); + virtual void onAnswerReceived(const EventBTRegisterRFCOMMPtr& event); + + virtual ~BluetoothAdapterListener(); +protected: + + virtual void OnAnswerReceived(const EventBTCreateDestroyBondingPtr& event); + virtual void OnAnswerReceived(const EventBTGetKnownDevicesPtr& event); + virtual void OnAnswerReceived(const EventBTGetDevicePtr& event); + virtual void OnAnswerReceived(const EventBTSetPoweredPtr& event); + virtual void OnAnswerReceived(const EventBTSetVisiblePtr& event); + virtual void OnAnswerReceived(const EventBTUnregisterRFCOMMServicePtr& event); + virtual void OnAnswerReceived(const EventBTStopDiscoveryPtr& event); + virtual void OnAnswerReceived(const EventBTSetNamePtr& event); + + +}; + +typedef DPL::SharedPtr BluetoothAdapterListenerPtr; + +} +} + +#endif diff --git a/src/standards/Tizen/Bluetooth/BluetoothClass.cpp b/src/standards/Tizen/Bluetooth/BluetoothClass.cpp new file mode 100644 index 0000000..e5711a9 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/BluetoothClass.cpp @@ -0,0 +1,256 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "BluetoothClass.h" +#include + +using namespace DPL; + +namespace TizenApis { +namespace Tizen1_0{ + +std::map BluetoothClass::m_serviceConstants; + +BluetoothClass::BluetoothClass() +{ + initConstants(); + m_readOnly = false; +} + +BluetoothClass::~BluetoothClass() +{ + +} + +void BluetoothClass::setReadOnly() +{ + m_readOnly = true; +} + +bool BluetoothClass::getReadOnly() +{ + return m_readOnly; +} + +bool BluetoothClass::find(const std::string key, int &value) +{ + if (m_serviceConstants.find(key) == m_serviceConstants.end()) + { + LogDebug("fetch error"); + return false; + } + + value = m_serviceConstants[key]; + LogDebug(key << ":" << value); + return true; +} + +int BluetoothClass::getMajor() +{ + return m_major; +} + +void BluetoothClass::setMajor(int major) +{ + m_major = major; +} + +int BluetoothClass::getMinor() +{ + return m_minor; +} + +void BluetoothClass::setMinor(int minor) +{ + m_minor = minor; +} + +std::vector BluetoothClass::getServices() +{ + return m_services; +} + +void BluetoothClass::setServices(int device) +{ + if (m_services.size() != 0) + { + m_services.clear(); + } + + std::map::iterator it; + int service = SERVICE_MASK_SHIFT(device); + + it = m_serviceConstants.find("LIMITED_DISCOVERABILITY"); + + if (it == m_serviceConstants.end()) + { + LogDebug("Invalid Service Mask Passed"); + return; + } + + for (; it != m_serviceConstants.end(); ++it) + { + if (service & (*it).second) + { + LogDebug("SERVICE " << (*it).first << " " << std::hex << (*it).second); + m_services.push_back((*it).second); + } + } + + if (m_services.size() == 0) + { + LogDebug("Invalid Service Mask Passed"); + } + +} + +unsigned long BluetoothClass::toInt() +{ + unsigned long uuid = 0; + + uuid = (m_major << MAJOR_SHIFT | m_minor << MINOR_SHIFT); + + LogDebug("major&minor" << std::hex << uuid); + + for (size_t index = 0; index < m_services.size(); index++) + { + uuid |= (m_services[index] << SERVICE_SHIFT); + } + + LogDebug("service" << std::hex << uuid); + + return uuid; +} +void BluetoothClass::fromInt(unsigned long device) +{ + if (m_readOnly) + { + LogDebug("static function, set error"); + return; + } + + LogDebug("device:" << std::hex << device); + + m_major = MAJOR_MASK_SHIFT(device); + m_minor = MINOR_MASK_SHIFT(device); + + LogDebug("major:" << std::hex << m_major << "minor:" << std::hex << m_minor); + + setServices(device); + +} + +void BluetoothClass::initConstants() +{ + if (m_serviceConstants.find("MISC") != m_serviceConstants.end()) + return; + + m_serviceConstants.insert(std::pair("MISC", 0x00)); + m_serviceConstants.insert(std::pair("COMPUTER", 0x01)); + m_serviceConstants.insert(std::pair("PHONE", 0x02)); + m_serviceConstants.insert(std::pair("NETWORK", 0x03)); + m_serviceConstants.insert(std::pair("AUDIO_VIDEO", 0x04)); + m_serviceConstants.insert(std::pair("PERIPHERAL", 0x05)); + m_serviceConstants.insert(std::pair("IMAGING", 0x06)); + m_serviceConstants.insert(std::pair("WEARABLE", 0x07)); + m_serviceConstants.insert(std::pair("TOY", 0x08)); + m_serviceConstants.insert(std::pair("HEALTH", 0x09)); + m_serviceConstants.insert(std::pair("UNCATEGORIZED", 0x1F)); + m_serviceConstants.insert(std::pair("COMPUTER_UNCATEGORIZED", 0x00)); + m_serviceConstants.insert(std::pair("COMPUTER_DESKTOP", 0x01)); + m_serviceConstants.insert(std::pair("COMPUTER_SERVER", 0x02)); + m_serviceConstants.insert(std::pair("COMPUTER_LAPTOP", 0x03)); + m_serviceConstants.insert(std::pair("COMPUTER_HANDHELD_PC_OR_PDA", 0x04)); + m_serviceConstants.insert(std::pair("COMPUTER_PALM_PC_OR_PDA", 0x5)); + m_serviceConstants.insert(std::pair("COMPUTER_WEARABLE", 0x06)); + m_serviceConstants.insert(std::pair("PHONE_UNCATEGORIZED", 0x00)); + m_serviceConstants.insert(std::pair("PHONE_CELLULAR", 0x01)); + m_serviceConstants.insert(std::pair("PHONE_CORDLESS", 0x02)); + m_serviceConstants.insert(std::pair("PHONE_SMARTPHONE", 0x03)); + m_serviceConstants.insert(std::pair("PHONE_MODEM_OR_GATEWAY", 0x04)); + m_serviceConstants.insert(std::pair("PHONE_ISDN", 0x05)); + m_serviceConstants.insert(std::pair("AV_UNRECOGINZED", 0x00)); + m_serviceConstants.insert(std::pair("AV_WEARABLE_HEADSET", 0x01)); + m_serviceConstants.insert(std::pair("AV_HANDSFREE", 0x02)); + m_serviceConstants.insert(std::pair("AV_MICROPHONE", 0x04)); + m_serviceConstants.insert(std::pair("AV_LOUDSPEAKER", 0x05)); + m_serviceConstants.insert(std::pair("AV_HEADPHONES", 0x06)); + m_serviceConstants.insert(std::pair("AV_PORTABLE_AUDIO", 0x07)); + m_serviceConstants.insert(std::pair("AV_CAR_AUDIO", 0x08)); + m_serviceConstants.insert(std::pair("AV_SETTOP_BOX", 0x09)); + m_serviceConstants.insert(std::pair("AV_HIFI", 0x0a)); + m_serviceConstants.insert(std::pair("AV_VCR", 0x0b)); + m_serviceConstants.insert(std::pair("AV_VIDEO_CAMERA", 0x0c)); + m_serviceConstants.insert(std::pair("AV_CAMCORDER", 0x0d)); + m_serviceConstants.insert(std::pair("AV_MONITOR", 0x0e)); + m_serviceConstants.insert(std::pair("AV_DISPLAY_AND_LOUDSPEAKER", 0x0f)); + m_serviceConstants.insert(std::pair("AV_VIDEO_CONFERENCING", 0x10)); + m_serviceConstants.insert(std::pair("AV_GAMING_TOY", 0x12)); + m_serviceConstants.insert(std::pair("PERIPHERAL_UNCATEGORIZED", 0)); + m_serviceConstants.insert(std::pair("PERIPHERAL_KEYBOARD", 0x10)); + m_serviceConstants.insert(std::pair("PERIPHERAL_POINTING_DEVICE", 0x20)); + m_serviceConstants.insert(std::pair("PERIPHERAL_KEYBOARD_AND_POINTING_DEVICE", 0x30)); + m_serviceConstants.insert(std::pair("PERIPHERAL_JOYSTICK", 0x01)); + m_serviceConstants.insert(std::pair("PERIPHERAL_GAMEPAD", 0x02)); + m_serviceConstants.insert(std::pair("PERIPHERAL_REMOTE_CONTROL", 0x03)); + m_serviceConstants.insert(std::pair("PERIPHERAL_SENSING_DEVICE", 0x04)); + m_serviceConstants.insert(std::pair("PERIPHERAL_DEGITIZER_TABLET", 0x05)); + m_serviceConstants.insert(std::pair("PERIPHERAL_CARD_READER", 0x06)); + m_serviceConstants.insert(std::pair("PERIPHERAL_DIGITAL_PEN", 0x07)); + m_serviceConstants.insert(std::pair("PERIPHERAL_HANDHELD_SCANNER", 0x08)); + m_serviceConstants.insert(std::pair("PERIPHERAL_HANDHELD_INPUT_DEVICE", 0x09)); + m_serviceConstants.insert(std::pair("IMAGING_UNCATEGORIZED", 0x00)); + m_serviceConstants.insert(std::pair("IMAGING_DISPLAY", 0x04)); + m_serviceConstants.insert(std::pair("IMAGING_CAMERA", 0x08)); + m_serviceConstants.insert(std::pair("IMAGING_SCANNER", 0x10)); + m_serviceConstants.insert(std::pair("IMAGING_PRINTER", 0x20)); + m_serviceConstants.insert(std::pair("WEARABLE_WRITST_WATCH", 0x01)); + m_serviceConstants.insert(std::pair("WEARABLE_PAGER", 0x02)); + m_serviceConstants.insert(std::pair("WEARABLE_JACKET", 0x03)); + m_serviceConstants.insert(std::pair("WEARABLE_HELMET", 0x04)); + m_serviceConstants.insert(std::pair("WEARABLE_GLASSES", 0x05)); + m_serviceConstants.insert(std::pair("TOY_ROBOT", 0x01)); + m_serviceConstants.insert(std::pair("TOY_VEHICLE", 0x02)); + m_serviceConstants.insert(std::pair("TOY_DOLL", 0x03)); + m_serviceConstants.insert(std::pair("TOY_CONTROLLER", 0x04)); + m_serviceConstants.insert(std::pair("TOY_GAME", 0x05)); + m_serviceConstants.insert(std::pair("HEALTH_UNDEFINED", 0x00)); + m_serviceConstants.insert(std::pair("HEALTH_BLOOD_PRESSURE_MONITOR", 0x01)); + m_serviceConstants.insert(std::pair("HEALTH_THERMOMETER", 0x02)); + m_serviceConstants.insert(std::pair("HEALTH_WEIGHING_SCALE", 0x03)); + m_serviceConstants.insert(std::pair("HEALTH_GLUCOSE_METER", 0x04)); + m_serviceConstants.insert(std::pair("HEALTH_PULSE_OXIMETER", 0x05)); + m_serviceConstants.insert(std::pair("HEALTH_PULSE_RATE_MONITOR", 0x06)); + m_serviceConstants.insert(std::pair("HEALTH_DATA_DISPLAY", 0x07)); + m_serviceConstants.insert(std::pair("HEALTH_STEP_COUNTER", 0x08)); + m_serviceConstants.insert(std::pair("HEALTH_BODY_COMPOSITION_ANALYZER", 0x09)); + m_serviceConstants.insert(std::pair("HEALTH_PEAK_FLOW_MONITOR", 0x0a)); + m_serviceConstants.insert(std::pair("HEALTH_MEDICATION_MONITOR", 0x0b)); + m_serviceConstants.insert(std::pair("HEALTH_KNEE_PROSTHESIS", 0x0c)); + m_serviceConstants.insert(std::pair("HEALTH_ANKLE_PROSTHESIS", 0x0d)); + m_serviceConstants.insert(std::pair("LIMITED_DISCOVERABILITY", 0x0001)); + m_serviceConstants.insert(std::pair("POSITIONING", 0x0008)); + m_serviceConstants.insert(std::pair("NETWORKING", 0x0010)); + m_serviceConstants.insert(std::pair("RENDERING", 0x0020)); + m_serviceConstants.insert(std::pair("CAPTURING", 0x0040)); + m_serviceConstants.insert(std::pair("OBJECT_TRANSFER", 0x0080)); + m_serviceConstants.insert(std::pair("AUDIO", 0x0100)); + m_serviceConstants.insert(std::pair("TELEPHONY", 0x0200)); + m_serviceConstants.insert(std::pair("INFORMATION", 0x0400)); +} +} +} + diff --git a/src/standards/Tizen/Bluetooth/BluetoothClass.h b/src/standards/Tizen/Bluetooth/BluetoothClass.h new file mode 100644 index 0000000..3505c68 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/BluetoothClass.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_TIZEN_BLUETOOTH_CLASS_H_ +#define TIZENAPIS_TIZEN_BLUETOOTH_CLASS_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +class BluetoothClass; +typedef DPL::SharedPtr BluetoothClassPtr; + +#define MAJOR_SHIFT 7 +#define MINOR_SHIFT 1 +#define SERVICE_SHIFT 12 + +#define MAJOR_MASK_SHIFT(A) ((A & 0x00000F80) >> MAJOR_SHIFT) +#define MINOR_MASK_SHIFT(A) ((A & 0x0000007E) >> MINOR_SHIFT) +#define SERVICE_MASK_SHIFT(A) ((A & 0x007FF000) >> SERVICE_SHIFT) + + +class BluetoothClass +{ +public: + bool find(const std::string key, int &value); + int getMajor(); + int getMinor(); + std::vector getServices(); + void setServices(int device); + void setMajor(int major); + void setMinor(int minor); + void fromInt(unsigned long value); + void setReadOnly(); + bool getReadOnly(); + unsigned long toInt(); + BluetoothClass(); + ~BluetoothClass(); +private: + void initConstants(); + static std::map m_serviceConstants; + std::vector m_services; + bool m_readOnly; + int m_major; + int m_minor; +}; +} +} +#endif diff --git a/src/standards/Tizen/Bluetooth/BluetoothConverter.cpp b/src/standards/Tizen/Bluetooth/BluetoothConverter.cpp new file mode 100644 index 0000000..b3c5a0a --- /dev/null +++ b/src/standards/Tizen/Bluetooth/BluetoothConverter.cpp @@ -0,0 +1,393 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include +#include +#include +#include +#include +#include +#include "BluetoothConverter.h" +#include "JSBluetoothDevice.h" + +#include + +using namespace std; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + + +namespace TizenApis { +namespace Tizen1_0 { + +BluetoothConverter::BluetoothConverter(JSContextRef context) : + Converter(context) +{ +} + +BluetoothConverter::~BluetoothConverter() +{ +} + + + +JSValueRef BluetoothConverter::toFunctionOrNull(const JSValueRef& arg) +{ + if (JSValueIsNull(m_context, arg)) + { + LogDebug("null."); + + return NULL; + } + else if (JSValueIsUndefined(m_context, arg) || JSValueIsObject(m_context, arg) == false) + { + LogDebug("undefined, not object"); + ThrowMsg(ConversionException, "Not a function nor JS null."); + } + else if (Validator(m_context).isCallback(arg)) + { + return arg; + } + + ThrowMsg(InvalidArgumentException, "unexpected argument"); + return NULL; +} + +JSValueRef BluetoothConverter::toFunction(const JSValueRef& arg) +{ + if (JSValueIsNull(m_context, arg) || JSValueIsUndefined(m_context, arg) + || !JSValueIsObject(m_context, arg)) + { + ThrowMsg(ConversionException, "JS null passed as function."); + } + else if (Validator(m_context).isCallback(arg)) + { + return arg; + } + + ThrowMsg(InvalidArgumentException, "Not a function nor JS null."); + return NULL; +} + + +EventBTOnDiscoveryDevicesPrivateDataPtr + BluetoothConverter::toEventBTOnDiscoveryDevicesPrivateData(JSObjectRef thisObject, JSValueRef successParam, JSValueRef errorParam) +{ + JSValueRef errorCalback; + if (JSValueIsNull(m_context, successParam) || JSValueIsUndefined(m_context, successParam) + || !JSValueIsObject(m_context, successParam)) + { + LogError("not a object"); + Throw(ConversionException); + } + + JSObjectRef objectCallbacks = toJSObjectRef(successParam); + Validator validator(m_context); + BluetoothDiscoveryDevicesSuccessCallback result; + + errorCalback = toFunctionOrNull(errorParam); + + result.onSuccess = JSUtils::getJSPropertyOrUndefined(m_context, objectCallbacks, "onSuccess"); + result.onFound = JSUtils::getJSPropertyOrUndefined(m_context, objectCallbacks, "onFound"); + result.onFinished = JSUtils::getJSPropertyOrUndefined(m_context, objectCallbacks, "onFinish"); + + if ((!validator.isNullOrUndefined(result.onSuccess) && !validator.isCallback(result.onSuccess)) || + (!validator.isNullOrUndefined(result.onFound) && !validator.isCallback(result.onFound)) || + (!validator.isNullOrUndefined(result.onFinished) && !validator.isCallback(result.onFinished))) + { + LogError("java script call back set error"); + Throw(ConversionException); + } + + JSCallbackManagerPtr onSuccessCbm = JSCallbackManager::createObject(m_context, result.onSuccess, NULL); + JSCallbackManagerPtr onFoundCbm = JSCallbackManager::createObject(m_context, result.onFound, NULL); + JSCallbackManagerPtr onFinishedCbm = JSCallbackManager::createObject(m_context, result.onFinished, NULL); + + onSuccessCbm->setObject(thisObject); + onFoundCbm->setObject(thisObject); + onFinishedCbm->setObject(thisObject); + onSuccessCbm->setOnError(errorCalback); + onFoundCbm->setOnError(errorCalback); + onFinishedCbm->setOnError(errorCalback); + + return EventBTOnDiscoveryDevicesPrivateDataPtr( + new EventBTOnDiscoveryDevicesPrivateData(onSuccessCbm, onFoundCbm, onFinishedCbm)); +} + +BluetoothSocketNotifierPrivateDataPtr + BluetoothConverter::toBluetoothSocketNotifierPrivateData(JSObjectRef thisObject, JSValueRef successParam) +{ + + if (JSValueIsNull(m_context, successParam) || JSValueIsUndefined(m_context, successParam) + || !JSValueIsObject(m_context, successParam)) + { + LogError("not a object"); + Throw(ConversionException); + } + + Validator validator(m_context); + JSObjectRef objectCallbacks = toJSObjectRef(successParam); + BluetoothSocketNotifier result; + + result.onMessage = JSUtils::getJSPropertyOrUndefined(m_context, objectCallbacks, "onMessage"); + result.onError = JSUtils::getJSPropertyOrUndefined(m_context, objectCallbacks, "onError"); + result.onClose = JSUtils::getJSPropertyOrUndefined(m_context, objectCallbacks, "onClose"); + + if ((!validator.isNullOrUndefined(result.onMessage) && !validator.isCallback(result.onMessage)) || + (!validator.isNullOrUndefined(result.onError) && !validator.isCallback(result.onError)) || + (!validator.isNullOrUndefined(result.onClose) && !validator.isCallback(result.onClose))) + { + LogError("java script call back set error"); + Throw(ConversionException); + } + + JSCallbackManagerPtr onMessageCbm = JSCallbackManager::createObject(m_context, result.onMessage, NULL); + JSCallbackManagerPtr onErrorCbm = JSCallbackManager::createObject(m_context, result.onError, NULL); + JSCallbackManagerPtr onCloseCbm = JSCallbackManager::createObject(m_context, result.onClose, NULL); + + onMessageCbm->setObject(thisObject); + onErrorCbm->setObject(thisObject); + onCloseCbm->setObject(thisObject); + + return BluetoothSocketNotifierPrivateDataPtr( + new BluetoothSocketNotifierPrivateData(onMessageCbm, onErrorCbm, onCloseCbm)); +} + +BluetoothRegisterServiceSuccessCallbackPrivateDataPtr + BluetoothConverter::toBluetoothRegisterServiceSuccessCallbackPrivateData( + JSObjectRef thisObject, JSValueRef successParam, JSValueRef errorParam) +{ + JSValueRef errorCalback; + + if (JSValueIsNull(m_context, successParam) || JSValueIsUndefined(m_context, successParam) + || !JSValueIsObject(m_context, successParam)) + { + LogError("not a object"); + Throw(ConversionException); + } + + Validator validator(m_context); + JSObjectRef objectCallbacks = toJSObjectRef(successParam); + BluetoothRegisterServiceSuccessCallback result; + + + errorCalback = toFunctionOrNull(errorParam); + + + result.onSuccess = JSUtils::getJSPropertyOrUndefined(m_context, objectCallbacks, "onSuccess"); + result.onConnected = JSUtils::getJSPropertyOrUndefined(m_context, objectCallbacks, "onConnect"); + + if ((!validator.isNullOrUndefined(result.onSuccess) && !validator.isCallback(result.onSuccess)) || + (!validator.isNullOrUndefined(result.onConnected) && !validator.isCallback(result.onConnected))) + { + LogError("java script call back set error"); + Throw(ConversionException); + } + JSCallbackManagerPtr onSuccess = JSCallbackManager::createObject(m_context, result.onSuccess, NULL); + JSCallbackManagerPtr onConnectedCbm = JSCallbackManager::createObject(m_context, result.onConnected, NULL); + + onSuccess->setObject(thisObject); + onConnectedCbm->setObject(thisObject); + onSuccess->setOnError(errorCalback); + onConnectedCbm->setOnError(errorCalback); + + return BluetoothRegisterServiceSuccessCallbackPrivateDataPtr( + new BluetoothRegisterServiceSuccessCallbackPrivateData(onSuccess, onConnectedCbm)); +} + +JSObjectRef BluetoothConverter::toBluetoothDevices(const std::vector& devices) +{ + int count = devices.size(); + int index = 0; + JSObjectRef adapterObject[count]; + + for (index = 0; index < count; index++) + { + adapterObject[index] = JSBluetoothDevice::createJSObject(m_context, devices[index]); + } + JSObjectRef result = JSObjectMakeArray(m_context, count, adapterObject, NULL); + return result; +} + +JSObjectRef BluetoothConverter::toBluetoothByteArray(std::vector& data) +{ + JSObjectRef result = JSCreateArrayObject(m_context, 0, NULL); + int length = data.size(); + + if (!result) + { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, "Could not create array object."); + } + + for (int i = 0; i < length; ++i) + { + JSValueRef value = JSValueMakeNumber(m_context, data[i]); + + if (!JSSetArrayElement(m_context, result, i, value)) + { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, "Could not fill array."); + } + } + return result; +} +std::string BluetoothConverter::toBluetoothDeviceAddress(JSValueRef deviceAddress) +{ + if (!JSValueIsString(m_context, deviceAddress) || JSValueIsNull(m_context, deviceAddress)) + { + ThrowMsg(ConversionException, "Not a string"); + } + + std::string address = toString(deviceAddress); + pcrecpp::RE re("(([0-9a-zA-Z]+):)+([0-9a-zA-Z]+)"); + std::string compareAddress = "00:12:47:08:9A:A6"; + + if (!re.FullMatch(address)) + { + ThrowMsg(ConversionException, "not a bluetooth device address"); + } + + if (address.size() != compareAddress.size()) + { + ThrowMsg(InvalidArgumentException, "too long or too short parameter"); + } + + return address; +} + +std::string BluetoothConverter::toBluetoothUUIDString(JSValueRef uuidString) +{ + if (!JSValueIsString(m_context, uuidString) || JSValueIsNull(m_context, uuidString)) + { + ThrowMsg(ConversionException, "Not a string"); + } + + std::string uuid = toString(uuidString); + pcrecpp::RE re("(([0-9a-zA-Z]+)-)+([0-9a-zA-Z]+)"); + std::string compareUUID = "00001101-0000-1000-8000-00805F9B34FB"; + + if (!re.FullMatch(uuid)) + { + LogDebug("not a bluetooth service uuid"); + ThrowMsg(ConversionException, "not a bluetooth service uuid"); + } + + if (uuid.size() != compareUUID.size()) + { + LogDebug("too long or too short parameter"); + ThrowMsg(InvalidArgumentException, "too long or too short parameter"); + } + + return uuid; +} + + + + + +unsigned short BluetoothConverter::toBluetoothSecurityLevelInt(JSValueRef level) +{ + unsigned short securityLevel= SECURITY_LEVEL_HIGH_VALUE_INT; + + if (!JSValueIsNull(m_context, level)) + { + if (!JSValueIsString(m_context, level)) + { + ThrowMsg(ConversionException, "Not a string"); + } + + std::string securityLevelStr = toString(level); + + if(strcmp(securityLevelStr.c_str(), SECURITY_LEVEL_HIGH_VALUE) == 0) + { + securityLevel = SECURITY_LEVEL_HIGH_VALUE_INT; + } + else + { + if (strcmp(securityLevelStr.c_str(), SECURITY_LEVEL_MEDIUM_VALUE) == 0 || + strcmp(securityLevelStr.c_str(), SECURITY_LEVEL_LOW_VALUE) == 0) + { + Throw(UnsupportedException); + } + else + { + Throw(ConversionException); + } + } + } + return securityLevel; +} + + + +JSValueRef BluetoothConverter::toBluetoothSecurityLevelJSValueRef(unsigned short level) +{ + JSValueRef result; + + switch (level) + { + case SECURITY_LEVEL_HIGH_VALUE_INT: + result = toJSValueRef(SECURITY_LEVEL_HIGH_VALUE); + break; + case SECURITY_LEVEL_MEDIUM_VALUE_INT: + result = toJSValueRef(SECURITY_LEVEL_MEDIUM_VALUE); + break; + case SECURITY_LEVEL_LOW_VALUE_INT: + result = toJSValueRef(SECURITY_LEVEL_LOW_VALUE); + break; + default: + result = toJSValueRef(SECURITY_LEVEL_HIGH_VALUE); + } + return result; +} + +JSValueRef BluetoothConverter::toBluetoothProtocolJSValue(unsigned short int protocol) +{ + if (protocol == PROTOCOL_TYPE_RFCOMM_VALUE_INT) + { + return toJSValueRef(PROTOCOL_TYPE_RFCOMM_VALUE); + + } + else if (protocol == PROTOCOL_TYPE_L2CAP_VALUE_INT) + { + return toJSValueRef(PROTOCOL_TYPE_L2CAP_VALUE); + } + else + { + ThrowMsg(ConversionException, "Not a protocol value"); + } +} + +JSValueRef BluetoothConverter::toBluetoothStateJSValue(unsigned short int state) +{ + if (state == SOCKET_STATE_CLOSED_VALUE_INT) + { + return toJSValueRef(SOCKET_STATE_CLOSED_VALUE); + + } + else if (state == SOCKET_STATE_OPEN_VALUE_INT) + { + return toJSValueRef(SOCKET_STATE_OPEN_VALUE); + } + else + { + ThrowMsg(ConversionException, "Not a state value"); + + } +} + +} +} + diff --git a/src/standards/Tizen/Bluetooth/BluetoothConverter.h b/src/standards/Tizen/Bluetooth/BluetoothConverter.h new file mode 100755 index 0000000..f8ea118 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/BluetoothConverter.h @@ -0,0 +1,60 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +#include +#include +#include +#include "BluetoothMultiCallback.h" + +#ifndef TIZENAPIS_TIZEN_BLUETOOTH_CONVERTER_H_ +#define TIZENAPIS_TIZEN_BLUETOOTH_CONVERTER_H_ + +namespace TizenApis { +namespace Tizen1_0 { + +class BluetoothConverter : public WrtDeviceApis::CommonsJavaScript::Converter +{ + public: + using WrtDeviceApis::CommonsJavaScript::Converter::toJSValueRef; + + explicit BluetoothConverter(JSContextRef context); + virtual ~BluetoothConverter(); + + JSValueRef toFunctionOrNull(const JSValueRef& arg); + JSValueRef toFunction(const JSValueRef& arg); + EventBTOnDiscoveryDevicesPrivateDataPtr + toEventBTOnDiscoveryDevicesPrivateData(JSObjectRef thisObject, + JSValueRef successParam, JSValueRef errorParam); + BluetoothSocketNotifierPrivateDataPtr + toBluetoothSocketNotifierPrivateData(JSObjectRef thisObject, JSValueRef successParam); + BluetoothRegisterServiceSuccessCallbackPrivateDataPtr + toBluetoothRegisterServiceSuccessCallbackPrivateData(JSObjectRef thisObject, + JSValueRef successParam, JSValueRef errorParam); + JSObjectRef toBluetoothDevices(const std::vector& devices); + JSObjectRef toBluetoothByteArray(std::vector& data); + unsigned short toBluetoothSecurityLevelInt(JSValueRef level); + JSValueRef toBluetoothSecurityLevelJSValueRef(unsigned short level); + std::string toBluetoothDeviceAddress(JSValueRef deviceAddress); + std::string toBluetoothUUIDString(JSValueRef uuidString); + JSValueRef toBluetoothProtocolJSValue(unsigned short int protocol); + JSValueRef toBluetoothStateJSValue(unsigned short int state); +}; +} +} + +#endif + diff --git a/src/standards/Tizen/Bluetooth/BluetoothDeviceManagerListener.cpp b/src/standards/Tizen/Bluetooth/BluetoothDeviceManagerListener.cpp new file mode 100755 index 0000000..58655cf --- /dev/null +++ b/src/standards/Tizen/Bluetooth/BluetoothDeviceManagerListener.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "BluetoothDeviceManagerListener.h" +#include "JSBluetoothSocket.h" + +using namespace TizenApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { + +BluetoothDeviceManagerListener::~BluetoothDeviceManagerListener() +{ + LogDebug("entered"); +} +BluetoothDeviceManagerListener::BluetoothDeviceManagerListener() : + EventBTConnectedAnswerReceiver(ThreadEnum::NULL_THREAD) +{ + LogDebug("entered"); +} + + +BluetoothDeviceManagerListener& BluetoothDeviceManagerListener::getInstance() +{ + static BluetoothDeviceManagerListener instance; + return instance; +} + +void BluetoothDeviceManagerListener::OnAnswerReceived(const EventBTConnectToServiceByUUIDPtr& event) +{ + LogDebug("Enter"); + JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast (event->getPrivateData()); + + if (event->getExceptionCode() == ExceptionCodes::None) + { + BluetoothSocketData socketData = event->getSocketData(); + socketData = event->getSocketData(); + JSObjectRef adapterObject = JSBluetoothSocket::createJSObject(callbackManager->getContext(), socketData); + callbackManager->callOnSuccess(adapterObject); + } + else + { + + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(callbackManager->getContext(), + JSTizenException::UNKNOWN_ERROR, "unknown error")); + } +} + +} +} + diff --git a/src/standards/Tizen/Bluetooth/BluetoothDeviceManagerListener.h b/src/standards/Tizen/Bluetooth/BluetoothDeviceManagerListener.h new file mode 100644 index 0000000..04ca73c --- /dev/null +++ b/src/standards/Tizen/Bluetooth/BluetoothDeviceManagerListener.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef TIZENAPIS_TIZEN_BLUETOOTH_DEVICE_MANAGER_LISTENER_H_ +#define TIZENAPIS_TIZEN_BLUETOOTH_DEVICE_MANAGER_LISTENER_H_ + +#include +#include +#include +#include + +using namespace TizenApis::Api; +using namespace TizenApis::Api::Bluetooth; +using namespace WrtDeviceApis::Commons; + + +namespace TizenApis { +namespace Tizen1_0 { + +typedef EventAnswerReceiver EventBTConnectedAnswerReceiver; + + +class BluetoothDeviceManagerListener : + public EventBTConnectedAnswerReceiver +{ +private: + BluetoothDeviceManagerListener(); +public: + static BluetoothDeviceManagerListener& getInstance(); + virtual ~BluetoothDeviceManagerListener(); +protected: + + virtual void OnAnswerReceived(const EventBTConnectToServiceByUUIDPtr& event); +}; + +typedef DPL::SharedPtr BluetoothDeviceManagerListenerPtr; + +} +} + +#endif + diff --git a/src/standards/Tizen/Bluetooth/BluetoothMultiCallback.cpp b/src/standards/Tizen/Bluetooth/BluetoothMultiCallback.cpp new file mode 100644 index 0000000..2b49488 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/BluetoothMultiCallback.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "BluetoothMultiCallback.h" + + +namespace TizenApis { +namespace Tizen1_0 { + +EventBTOnDiscoveryDevicesPrivateData::EventBTOnDiscoveryDevicesPrivateData + (const JSCallbackManagerPtr& onSuccess, const JSCallbackManagerPtr& onFound, + const JSCallbackManagerPtr& onFinished) : + m_onSuccess(onSuccess), m_onFound(onFound), m_onFinished(onFinished) {} + +JSCallbackManagerPtr EventBTOnDiscoveryDevicesPrivateData::getOnSuccess() const +{ + return m_onSuccess; +} + +JSCallbackManagerPtr EventBTOnDiscoveryDevicesPrivateData::getOnFound() const +{ + return m_onFound; +} + +JSCallbackManagerPtr EventBTOnDiscoveryDevicesPrivateData::getOnFinished() const +{ + return m_onFinished; +} + + +BluetoothSocketNotifierPrivateData::BluetoothSocketNotifierPrivateData + (const JSCallbackManagerPtr& onMessage, const JSCallbackManagerPtr& onError, + const JSCallbackManagerPtr& onClose) : + m_onMessage(onMessage), m_onError(onError), m_onClose(onClose) {} + +JSCallbackManagerPtr BluetoothSocketNotifierPrivateData::getOnMessage() const +{ + return m_onMessage; +} + +JSCallbackManagerPtr BluetoothSocketNotifierPrivateData::getOnError() const +{ + return m_onError; +} + +JSCallbackManagerPtr BluetoothSocketNotifierPrivateData::getOnClose() const +{ + return m_onClose; +} + + +BluetoothRegisterServiceSuccessCallbackPrivateData ::BluetoothRegisterServiceSuccessCallbackPrivateData + (const JSCallbackManagerPtr& onSuccess, const JSCallbackManagerPtr& onConnected) : + m_onSuccess(onSuccess), m_onConnected(onConnected) {} + + +JSCallbackManagerPtr BluetoothRegisterServiceSuccessCallbackPrivateData::getOnSuccess() const +{ + return m_onSuccess; +} + +JSCallbackManagerPtr BluetoothRegisterServiceSuccessCallbackPrivateData::getOnConnected() const +{ + return m_onConnected; +} + +} +} + + + + diff --git a/src/standards/Tizen/Bluetooth/BluetoothMultiCallback.h b/src/standards/Tizen/Bluetooth/BluetoothMultiCallback.h new file mode 100644 index 0000000..19bc74a --- /dev/null +++ b/src/standards/Tizen/Bluetooth/BluetoothMultiCallback.h @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_BLUETOOTH_MULTI_CALLBACK_H_ +#define TIZENAPIS_TIZEN_BLUETOOTH_MULTI_CALLBACK_H_ + +#include +#include +#include +#include + +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +struct BluetoothDiscoveryDevicesSuccessCallback +{ + JSValueRef onSuccess; + JSValueRef onFound; + JSValueRef onFinished; + + BluetoothDiscoveryDevicesSuccessCallback() + : onSuccess(NULL), + onFound(NULL), + onFinished(NULL) + { } +}; + +struct BluetoothSocketNotifier +{ + JSValueRef onMessage; + JSValueRef onError; + JSValueRef onClose; + + BluetoothSocketNotifier() + : onMessage(NULL), + onError(NULL), + onClose(NULL) + { } + +}; + +struct BluetoothRegisterServiceSuccessCallback +{ + JSValueRef onSuccess; + JSValueRef onConnected; + + BluetoothRegisterServiceSuccessCallback() + : onSuccess(NULL), + onConnected(NULL) + { } +}; + + +class EventBTOnDiscoveryDevicesPrivateData : public WrtDeviceApis::Commons::IEventPrivateData +{ +public: + EventBTOnDiscoveryDevicesPrivateData(const JSCallbackManagerPtr& onSuccess, + const JSCallbackManagerPtr& onFound, + const JSCallbackManagerPtr& onFinished); + + JSCallbackManagerPtr getOnSuccess() const; + JSCallbackManagerPtr getOnFound() const; + JSCallbackManagerPtr getOnFinished() const; + +private: + JSCallbackManagerPtr m_onSuccess; + JSCallbackManagerPtr m_onFound; + JSCallbackManagerPtr m_onFinished; +}; + +typedef DPL::SharedPtr EventBTOnDiscoveryDevicesPrivateDataPtr; + + +class BluetoothSocketNotifierPrivateData : public WrtDeviceApis::Commons::IEventPrivateData +{ +public: + BluetoothSocketNotifierPrivateData + (const JSCallbackManagerPtr& onMessage, + const JSCallbackManagerPtr& onError, + const JSCallbackManagerPtr& onClose); + + JSCallbackManagerPtr getOnMessage() const; + JSCallbackManagerPtr getOnError() const; + JSCallbackManagerPtr getOnClose() const; + +private: + JSCallbackManagerPtr m_onMessage; + JSCallbackManagerPtr m_onError; + JSCallbackManagerPtr m_onClose; +}; + +typedef DPL::SharedPtr BluetoothSocketNotifierPrivateDataPtr; + + +class BluetoothRegisterServiceSuccessCallbackPrivateData : public WrtDeviceApis::Commons::IEventPrivateData +{ +public: + BluetoothRegisterServiceSuccessCallbackPrivateData + (const JSCallbackManagerPtr& onSuccess, const JSCallbackManagerPtr& onConnected); + + JSCallbackManagerPtr getOnSuccess() const; + JSCallbackManagerPtr getOnConnected() const; + +private: + JSCallbackManagerPtr m_onSuccess; + JSCallbackManagerPtr m_onConnected; +}; + +typedef DPL::SharedPtr BluetoothRegisterServiceSuccessCallbackPrivateDataPtr; +} +} + +#endif diff --git a/src/standards/Tizen/Bluetooth/BluetoothSocketListener.cpp b/src/standards/Tizen/Bluetooth/BluetoothSocketListener.cpp new file mode 100644 index 0000000..8301803 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/BluetoothSocketListener.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "BluetoothSocketListener.h" +#include "BluetoothMultiCallback.h" +#include "JSBluetoothSocket.h" + +using namespace TizenApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { + +BluetoothSocketListener::~BluetoothSocketListener() +{ + LogDebug("entered"); +} +BluetoothSocketListener::BluetoothSocketListener() : + EventBTSocketNotificationListener(ThreadEnum::NULL_THREAD) +{ + LogDebug("entered"); + +} + +BluetoothSocketListener& BluetoothSocketListener::getInstance() +{ + static BluetoothSocketListener instance; + return instance; + +} + +void BluetoothSocketListener::onAnswerReceived(const EventBTSocketNotificationPtr& event) +{ + LogDebug("Enter-Socket notification"); + + BluetoothSocketNotifierPrivateDataPtr multiCallbacks = + DPL::DynamicPointerCast(event->getPrivateData()); + BluetoothSocketData socketData = event->getSocketData(); + EventBTReadDataType readData; + JSObjectRef adapterObject; + + + switch(event->getConnectionState()) + { + case EventBTSocketNotification::DISCONNECTED: + adapterObject = JSBluetoothSocket::createJSObject(multiCallbacks->getOnClose()->getContext(), socketData); + multiCallbacks->getOnClose()->callOnSuccess(adapterObject); + break; + case EventBTSocketNotification::DATARECEIVED: + readData = event->getReadData(); + adapterObject = JSBluetoothSocket::createJSObject(multiCallbacks->getOnMessage()->getContext(), socketData, readData); + multiCallbacks->getOnMessage()->callOnSuccess(adapterObject); + break; + case EventBTSocketNotification::SOCKETERROR: + default: + adapterObject = JSBluetoothSocket::createJSObject(multiCallbacks->getOnError()->getContext(), socketData); + JSValueRef socketCallbackArray[2] = {JSTizenExceptionFactory::makeErrorObject(multiCallbacks->getOnError()->getContext(), + JSTizenException::UNKNOWN_ERROR, "unknown error"), adapterObject}; + multiCallbacks->getOnError()->callOnSuccess(socketCallbackArray, 2); + break; + } +} +} +} diff --git a/src/standards/Tizen/Bluetooth/BluetoothSocketListener.h b/src/standards/Tizen/Bluetooth/BluetoothSocketListener.h new file mode 100644 index 0000000..363090f --- /dev/null +++ b/src/standards/Tizen/Bluetooth/BluetoothSocketListener.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_BLUETOOTH_SOCKET_LISTENER_H_ +#define TIZENAPIS_TIZEN_BLUETOOTH_SOCKET_LISTENER_H_ + +#include +#include +#include +#include +#include +#include + + +using namespace TizenApis::Api; +using namespace TizenApis::Api::Bluetooth; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +typedef EventListener EventBTSocketNotificationListener; +class BluetoothSocketListener : + public EventBTSocketNotificationListener +{ +public: + BluetoothSocketListener(); + static BluetoothSocketListener& getInstance(); + virtual void onAnswerReceived(const EventBTSocketNotificationPtr& event); + virtual ~BluetoothSocketListener(); +}; + +typedef DPL::SharedPtr BluetoothSocketListenerPtr; + +} +} + +#endif diff --git a/src/standards/Tizen/Bluetooth/CMakeLists.txt b/src/standards/Tizen/Bluetooth/CMakeLists.txt new file mode 100755 index 0000000..0ff4948 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/CMakeLists.txt @@ -0,0 +1,42 @@ +set(TARGET_NAME "wrt-plugins-tizen-1.0-bluetooth") + +include_directories(${INCLUDES_PLATFORM_IMPLEMENTATION_BLUETOOTH}) + +#set(LIBS_PLATFORM_IMPLEMENTATION_BLUETOOTH +# ${LIBS_PLATFORM_IMPLEMENTATION_BLUETOOTH} +#) + + +set(SRCS + ${SRCS_PLATFORM_IMPLEMENTATION_BLUETOOTH} + ${SRCS_PLATFORM_API_BLUETOOTH} + ../Common/JSTizenException.cpp + ../Common/TizenExceptionData.cpp + ../Common/JSTizenExceptionFactory.cpp + plugin_initializer.cpp + plugin_config.cpp + BluetoothAdapterListener.cpp + JSBluetoothAdapter.cpp + JSBluetoothDevice.cpp + BluetoothSocketListener.cpp + BluetoothDeviceManagerListener.cpp + JSBluetoothClass.cpp + JSBluetoothClassDeviceMajor.cpp + JSBluetoothClassDeviceMinor.cpp + JSBluetoothClassDeviceService.cpp + JSBluetoothManager.cpp + BluetoothClass.cpp + JSBluetoothSocket.cpp + JSBluetoothDevice.cpp + BluetoothMultiCallback.cpp + BluetoothConverter.cpp +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMON} + ${LIBS_PLATFORM_IMPLEMENTATION_BLUETOOTH} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION tizen-1.0-bluetooth) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION tizen-1.0-bluetooth) diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothAdapter.cpp b/src/standards/Tizen/Bluetooth/JSBluetoothAdapter.cpp new file mode 100644 index 0000000..4478cb5 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothAdapter.cpp @@ -0,0 +1,1422 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "JSBluetoothAdapter.h" +#include +#include +#include +#include "BluetoothAdapterListener.h" +#include "BluetoothMultiCallback.h" +#include "BluetoothConverter.h" + +#include "plugin_config.h" + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Commons; + + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassRef JSBluetoothAdapter::m_jsClassRef = NULL; + +JSClassDefinition JSBluetoothAdapter::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "BluetoothAdapter", + NULL, + m_properties, + m_function, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + hasInstance, + NULL +}; + +JSStaticFunction JSBluetoothAdapter::m_function[] = +{ + { "setPowered", JSBluetoothAdapter::setPowered, kJSPropertyAttributeNone }, + { "setVisible", JSBluetoothAdapter::setVisible, kJSPropertyAttributeNone }, + { "setName", JSBluetoothAdapter::setName, kJSPropertyAttributeNone }, + { "discoverDevices", JSBluetoothAdapter::discoveryDevices, kJSPropertyAttributeNone }, + { "stopDiscovery", JSBluetoothAdapter::stopDiscovery, kJSPropertyAttributeNone }, + { "getKnownDevices", JSBluetoothAdapter::getKnownDevices, kJSPropertyAttributeNone }, + { "getDevice", JSBluetoothAdapter::getDevice, kJSPropertyAttributeNone }, + { "createBonding", JSBluetoothAdapter::createBonding, kJSPropertyAttributeNone }, + { "destroyBonding", JSBluetoothAdapter::destroyBonding, kJSPropertyAttributeNone }, + { "registerRFCOMMServiceByUUID", JSBluetoothAdapter::registerRFCOMMServiceByUUID, kJSPropertyAttributeNone }, + { "unregisterRFCOMMService", JSBluetoothAdapter::unregisterRFCOMMService, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSStaticValue JSBluetoothAdapter::m_properties[] = { + {"address", getAddress, NULL, kJSPropertyAttributeReadOnly}, + {"name", getName, NULL, kJSPropertyAttributeReadOnly}, + {"powered", getPowered, NULL, kJSPropertyAttributeReadOnly}, + {"visible", getVisible, NULL, kJSPropertyAttributeReadOnly}, + + {0, 0, 0, 0} +}; + +JSValueRef JSBluetoothAdapter::getName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + + Converter converter(context); + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(object)); + + Try + { + if (priv == NULL) + { + Throw(UnknownException); + } + + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + std::string name = BluetoothAdapterManager->getName(); + return converter.toJSValueRef(name); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSBluetoothAdapter::setName(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Enter"); + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + JSValueRef successCallback = NULL; + JSValueRef errorCallBack = NULL; + + + Try + { + if (priv == NULL) + { + Throw(UnknownException); + } + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADAPTER_SET_NAME]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount < 2 || argumentCount > 3) + { + Throw(InvalidArgumentException); + } + + if (JSValueIsNull(context, arguments[0]) == true || JSValueIsString(context, arguments[0]) == false) + { + Throw(ConversionException); + } + + BluetoothConverter converter(priv->getContext()); + successCallback = converter.toFunction(arguments[1]); + + if (argumentCount >= 3) + { + errorCallBack = converter.toFunctionOrNull(arguments[2]); + } + + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(priv->getContext(), NULL, NULL); + + if (cbm == NULL) + { + Throw(UnknownException); + } + + cbm->setOnSuccess(successCallback); + cbm->setOnError(errorCallBack); + cbm->setObject(thisObject); + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + std::string name = converter.toString(arguments[0]); + + if (name != BluetoothAdapterManager->getName()) + { + EventBTSetNamePtr event(new EventBTSetName); + + event->setPrivateData(DPL::StaticPointerCast (cbm)); + BluetoothAdapterListener& listener = BluetoothAdapterListener::getInstance(); + event->setForAsynchronousCall(&listener); + event->setName(name); + BluetoothAdapterManager->setAdapterName(event); + } + else + { + LogDebug("same name is already set"); + cbm->callOnSuccess(); + } + return JSValueMakeNull(context); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSBluetoothAdapter::getAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + + Converter converter(context); + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(object)); + + Try + { + if (priv == NULL) + { + Throw(UnknownException); + } + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + std::string address = BluetoothAdapterManager->getAddress(); + return converter.toJSValueRef(address); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + + } + return JSValueMakeUndefined(context); + +} + + +JSValueRef JSBluetoothAdapter::getVisible(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + + Converter converter(context); + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(object)); + Try + { + if (priv == NULL) + { + Throw(UnknownException); + } + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + bool visibility = BluetoothAdapterManager->getVisibility(); + return converter.toJSValueRef(visibility); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + return JSValueMakeUndefined(context); + +} + + + +const JSClassRef JSBluetoothAdapter::getClassRef() +{ + if (!m_jsClassRef) + { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSBluetoothAdapter::getClassInfo() +{ + return &m_classInfo; +} + + +void JSBluetoothAdapter::initialize(JSContextRef context, JSObjectRef object) +{ + JSBluetoothAdapterPriv* priv = static_cast(JSObjectGetPrivate(object)); + + if (priv != NULL) + { + LogDebug("Already Exist"); + } + else + { + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(BluetoothFactory::getInstance().getBluetoothAdapterManager()); + priv = new JSBluetoothAdapterPriv( context, BluetoothAdapterManager); + if(!JSObjectSetPrivate(object, static_cast(priv))) + { + LogError("Object can't store private data."); + delete priv; + } + LogDebug("JSBluetoothAdapter::initialize "); + } +} + +void JSBluetoothAdapter::finalize(JSObjectRef object) +{ + LogDebug("JSBluetoothAdapter::Finalrize"); + + JSBluetoothAdapterPriv* priv = static_cast(JSObjectGetPrivate(object)); + + if (priv != NULL) + { + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting BluetoothAdapterManager"); + delete priv; + } + + +} + +bool JSBluetoothAdapter::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + + +JSObjectRef JSBluetoothAdapter::createJSObject(JSContextRef context) +{ + IBluetoothAdapterManagerPtr BluetoothAdapterManager(BluetoothFactory::getInstance().getBluetoothAdapterManager()); + JSBluetoothAdapterPriv* priv = new JSBluetoothAdapterPriv( context, BluetoothAdapterManager); + + return JSObjectMake(context, getClassRef(), priv); + +} + +JSValueRef JSBluetoothAdapter::getPowered(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) + +{ + LogDebug("Enter"); + + Converter converter(context); + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(object)); + + Try + { + if (priv == NULL) + { + Throw(UnknownException); + } + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + bool powered = BluetoothAdapterManager->getPowered(); + return converter.toJSValueRef(powered); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSBluetoothAdapter::setPowered(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + + LogDebug("setPowered"); + + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + JSValueRef successCallback = NULL; + JSValueRef errorCallBack = NULL; + + Try + { + if (priv == NULL) + { + LogError("priv null"); + Throw(UnknownException); + } + + LogDebug(bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADAPTER_SET_POWERED]); + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADAPTER_SET_POWERED]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount < 2 || argumentCount > 3) + { + Throw(InvalidArgumentException); + } + + if (JSValueIsNull(context, arguments[0]) == true || JSValueIsBoolean(context, arguments[0]) == false) + { + Throw(ConversionException); + } + + BluetoothConverter converter(priv->getContext()); + successCallback = converter.toFunction(arguments[1]); + + if (argumentCount >= 3) + { + errorCallBack = converter.toFunctionOrNull(arguments[2]); + } + + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(priv->getContext(), NULL, NULL); + + if (cbm == NULL) + { + Throw(UnknownException); + } + cbm->setOnSuccess(successCallback); + cbm->setOnError(errorCallBack); + cbm->setObject(thisObject); + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + EventBTSetPoweredPtr event(new EventBTSetPowered); + + if (BluetoothAdapterManager == NULL || event == NULL) + { + LogError("BluetoothAdapterManager or event or listener NULL"); + Throw(UnknownException); + } + + if (converter.toBool(arguments[0]) == true) + { + event->setEnable(); + } + else + { + event->setDisable(); + } + + event->setPrivateData(DPL::StaticPointerCast (cbm)); + BluetoothAdapterListener& listener = BluetoothAdapterListener::getInstance(); + event->setForAsynchronousCall(&listener); + BluetoothAdapterManager->setPowered(event); + return JSValueMakeNull(context); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "unknown error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSBluetoothAdapter::setVisible(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + JSValueRef successCallback = NULL; + JSValueRef errorCallBack = NULL; + + Try + { + if (priv == NULL) + { + LogError("priv null"); + Throw(UnknownException); + } + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADAPTER_SET_VISIBLE]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + if (argumentCount < 2 || argumentCount > 4) + { + Throw(InvalidArgumentException); + } + BluetoothConverter converter(priv->getContext()); + successCallback = converter.toFunction(arguments[1]); + + if (argumentCount >= 3) + { + errorCallBack = converter.toFunctionOrNull(arguments[2]); + } + + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(priv->getContext(), NULL, NULL); + + if (cbm == NULL) + { + Throw(UnknownException); + } + + cbm->setOnSuccess(successCallback); + cbm->setOnError(errorCallBack); + cbm->setObject(thisObject); + + if (JSValueIsNull(context, arguments[0]) == true || JSValueIsBoolean(context, arguments[0]) == false) + { + LogError("Wrong parameter passed, type mismatch"); + Throw(ConversionException); + } + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + EventBTSetVisiblePtr event(new EventBTSetVisible); + + if (BluetoothAdapterManager == NULL || event == NULL) + { + LogError("BluetoothAdapterManager or event or listener NULL"); + Throw(UnknownException); + } + + if (converter.toBool(arguments[0]) == true) + { + event->setVisible(); + } + else + { + event->setInvisible(); + } + + if (argumentCount == 4) + { + if (JSValueIsNull(context, arguments[3]) == true) + { + event->setTimeout(0); + } + else + { + if (JSValueIsNumber(context, arguments[3]) == false) + { + LogError("Wrong parameter passed"); + Throw(ConversionException); + } + + LogDebug("timeout " << (unsigned short)converter.toInt(arguments[3])); + event->setTimeout((unsigned short)converter.toInt(arguments[3])); + } + } + else + { + event->setTimeout(0); + } + + event->setPrivateData(DPL::StaticPointerCast (cbm)); + BluetoothAdapterListener& listener = BluetoothAdapterListener::getInstance(); + event->setForAsynchronousCall(&listener); + BluetoothAdapterManager->setVisible(event); + + return JSValueMakeNull(context); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "unknown error"); + + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSBluetoothAdapter::discoveryDevices(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("discoveryDevices"); + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + + Try + { + if (priv == NULL) + { + LogError("priv null"); + Throw(UnknownException); + } + + if (argumentCount < 1 || argumentCount > 2) + { + LogError("InvalidArgumentException"); + Throw(InvalidArgumentException); + } + + LogDebug(bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADAPTER_DISCOVER_DEVICES]); + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADAPTER_DISCOVER_DEVICES]); + + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + JSValueRef errorArgument = JSValueMakeNull(context); + + if (argumentCount >= 2) + { + errorArgument = arguments[1]; + } + + BluetoothConverter converter(priv->getContext()); + EventBTOnDiscoveryDevicesPrivateDataPtr privData( + converter.toEventBTOnDiscoveryDevicesPrivateData(thisObject, arguments[0], errorArgument)); + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + EventBTOnDiscoveryDevicesEmitterPtr emitter(new EventBTOnDiscoveryDevicesEmitter); + + if (BluetoothAdapterManager == NULL || emitter == NULL || privData == NULL) + { + LogError("BluetoothAdapterManager or event or listener NULL"); + Throw(UnknownException); + } + emitter->setListener(&BluetoothAdapterListener::getInstance()); + emitter->setEventPrivateData(DPL::StaticPointerCast(privData)); + BluetoothAdapterManager->discoveryDevicesEmitter(emitter); + + return JSValueMakeNull(context); + + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "unknown error"); + } + return JSValueMakeUndefined(context); + +} + +JSValueRef JSBluetoothAdapter::stopDiscovery(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("discoveryDevices"); + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + JSValueRef successCallback = NULL; + JSValueRef errorCallBack = NULL; + + + Try + { + if (priv == NULL) + { + LogError("priv null"); + Throw(UnknownException); + } + + LogDebug(bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADAPTER_STOP_DISCOVERY]); + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADAPTER_STOP_DISCOVERY]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount < 1 || argumentCount > 2) + { + LogError("InvalidArgumentException"); + Throw(InvalidArgumentException); + } + + BluetoothConverter converter(priv->getContext()); + successCallback = converter.toFunction(arguments[0]); + + if (argumentCount >= 2) + { + errorCallBack = converter.toFunctionOrNull(arguments[1]); + } + + + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(priv->getContext(), NULL, NULL); + + if (cbm == NULL) + { + Throw(UnknownException); + } + + cbm->setOnSuccess(successCallback); + cbm->setOnError(errorCallBack); + cbm->setObject(thisObject); + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + EventBTStopDiscoveryPtr event(new EventBTStopDiscovery); + + event->setPrivateData(DPL::StaticPointerCast (cbm)); + BluetoothAdapterListener& listener = BluetoothAdapterListener::getInstance(); + event->setForAsynchronousCall(&listener); + BluetoothAdapterManager->stopDiscovery(event); + + return JSValueMakeNull(context); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "unknown error"); + + } + + return JSValueMakeUndefined(context); + +} + + +JSValueRef JSBluetoothAdapter::getKnownDevices(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("getKnownDevices"); + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + JSValueRef successCallback = NULL; + JSValueRef errorCallBack = NULL; + + Try + { + if (priv == NULL) + { + LogError("priv null"); + Throw(UnknownException); + } + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADAPTER_GET_KNOWN_DEVICES]); + + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount < 1 || argumentCount > 2) + { + LogError("InvalidArgumentException"); + Throw(InvalidArgumentException); + } + + BluetoothConverter converter(priv->getContext()); + successCallback = converter.toFunction(arguments[0]); + + if (argumentCount >= 2) + { + errorCallBack = converter.toFunctionOrNull(arguments[1]); + } + + + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(priv->getContext(), NULL, NULL); + + if (cbm == NULL) + { + Throw(UnknownException); + } + + cbm->setOnSuccess(successCallback); + cbm->setOnError(errorCallBack); + cbm->setObject(thisObject); + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + EventBTGetKnownDevicesPtr event(new EventBTGetKnownDevices); + + + if (BluetoothAdapterManager == NULL || event == NULL) + { + LogError("BluetoothAdapterManager or event or listener NULL"); + Throw(UnknownException); + } + + event->setPrivateData(DPL::StaticPointerCast (cbm)); + BluetoothAdapterListener& listener = BluetoothAdapterListener::getInstance(); + event->setForAsynchronousCall(&listener); + BluetoothAdapterManager->getKownDevices(event); + + return JSValueMakeNull(context); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "unknown error"); + + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSBluetoothAdapter::getDevice(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Enter"); + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + JSValueRef successCallback = NULL; + JSValueRef errorCallBack = NULL; + + + Try + { + if (priv == NULL) + { + LogError("priv null"); + Throw(UnknownException); + } + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADAPTER_GET_DEVICE]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + if (argumentCount < 2 || argumentCount > 3) + { + LogError("Wrong parameter count passed"); + Throw(InvalidArgumentException); + } + + BluetoothConverter converter(priv->getContext()); + std::string address = converter.toBluetoothDeviceAddress(arguments[0]); + successCallback = converter.toFunction(arguments[1]); + + if (argumentCount >= 3) + { + errorCallBack = converter.toFunctionOrNull(arguments[2]); + } + + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(priv->getContext(), NULL, NULL); + + if (cbm == NULL) + { + Throw(UnknownException); + } + + cbm->setOnSuccess(successCallback); + cbm->setOnError(errorCallBack); + cbm->setObject(thisObject); + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + EventBTGetDevicePtr event(new EventBTGetDevice); + + if (BluetoothAdapterManager == NULL || event == NULL) + { + LogError("BluetoothAdapterManager or event or listener NULL"); + Throw(UnknownException); + } + + event->setPrivateData(DPL::StaticPointerCast (cbm)); + BluetoothAdapterListener& listener = BluetoothAdapterListener::getInstance(); + event->setForAsynchronousCall(&listener); + event->setAddress(address); + BluetoothAdapterManager->getDevice(event); + + return JSValueMakeNull(context); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "unknown error"); + + } + + return JSValueMakeUndefined(context); +} + + +JSValueRef JSBluetoothAdapter::createBonding(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("createBonding"); + + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + JSValueRef successCallback = NULL; + JSValueRef errorCallBack = NULL; + + Try + { + + if (priv == NULL) + { + LogError("priv null"); + Throw(UnknownException); + } + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADPATER_CREATE_BONDING]); + + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount < 2 || argumentCount > 3) + { + LogError("Wrong parameter count passed"); + Throw(InvalidArgumentException); + + } + + + BluetoothConverter converter(priv->getContext()); + std::string address = converter.toBluetoothDeviceAddress(arguments[0]); + successCallback = converter.toFunction(arguments[1]); + + if (argumentCount >= 3) + { + errorCallBack = converter.toFunctionOrNull(arguments[2]); + } + + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(priv->getContext(), NULL, NULL); + + if (cbm == NULL) + { + Throw(UnknownException); + } + + cbm->setOnSuccess(successCallback); + cbm->setOnError(errorCallBack); + cbm->setObject(thisObject); + + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + EventBTCreateDestroyBondingPtr event(new EventBTCreateDestroyBonding); + + if (BluetoothAdapterManager == NULL || event == NULL) + { + LogError("BluetoothAdapterManager or event or listener NULL"); + Throw(UnknownException); + } + + event->setPrivateData(DPL::StaticPointerCast (cbm)); + BluetoothAdapterListener& listener = BluetoothAdapterListener::getInstance(); + event->setForAsynchronousCall(&listener); + event->setAddress(address); + event->setCreateBonding(); + BluetoothAdapterManager->createBonding(event); + return JSValueMakeNull(context); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "unknown error"); + + } + return JSValueMakeUndefined(context); + +} + +JSValueRef JSBluetoothAdapter::destroyBonding(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + + LogDebug("destroyBonding"); + + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + JSValueRef successCallback = NULL; + JSValueRef errorCallBack = NULL; + + Try + { + if (priv == NULL) + { + LogError("priv null"); + Throw(UnknownException); + } + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADPATER_DESTROY_BONDING]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount < 2 || argumentCount > 3) + { + LogError("Wrong parameter count passed"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + + BluetoothConverter converter(priv->getContext()); + std::string address = converter.toBluetoothDeviceAddress(arguments[0]); + successCallback = converter.toFunction(arguments[1]); + + if (argumentCount >= 3) + { + errorCallBack = converter.toFunctionOrNull(arguments[2]); + } + + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(priv->getContext(), NULL, NULL); + + if (cbm == NULL) + { + Throw(UnknownException); + } + + cbm->setOnSuccess(successCallback); + cbm->setOnError(errorCallBack); + cbm->setObject(thisObject); + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + EventBTCreateDestroyBondingPtr event(new EventBTCreateDestroyBonding); + + if (BluetoothAdapterManager == NULL || event == NULL) + { + LogError("BluetoothAdapterManager or event or listener NULL"); + Throw(UnknownException); + } + + BluetoothAdapterListener& listener = BluetoothAdapterListener::getInstance(); + event->setPrivateData(DPL::StaticPointerCast (cbm)); + event->setForAsynchronousCall(&listener); + event->setDestroyBonding(); + event->setAddress(address); + BluetoothAdapterManager->createBonding(event); + + return JSValueMakeNull(context); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "unknown error"); + + } + + return JSValueMakeUndefined(context); +} + + +JSValueRef JSBluetoothAdapter::registerRFCOMMServiceByUUID(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("registerRFCOMMServiceByUUID"); + + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + + Try + { + std::string serviceName, uuid; + unsigned short securityLevel= SECURITY_LEVEL_HIGH_VALUE_INT; + Validator validator(context); + int serviceSocketFd = -1; + + + if (priv == NULL) + { + LogError("priv null"); + Throw(UnknownException); + } + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADPATER_REGISTER_RFCOMM]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + if (argumentCount < 3 || argumentCount > 5) + { + LogError("Wrong parameter count passed"); + Throw(InvalidArgumentException); + } + + + JSValueRef errorArgument = JSValueMakeNull(context); + BluetoothConverter converter(priv->getContext()); + uuid = converter.toBluetoothUUIDString(arguments[0]); + + if (!JSValueIsString(context, arguments[1]) || JSValueIsNull(context, arguments[1])) + { + ThrowMsg(ConversionException, "Not a string"); + } + + serviceName = converter.toString(arguments[1]); + + if (argumentCount >= 4) + { + errorArgument = arguments[3]; + } + + if (argumentCount >= 5) + { + securityLevel = converter.toBluetoothSecurityLevelInt(arguments[4]); + } + + + BluetoothRegisterServiceSuccessCallbackPrivateDataPtr privData( + converter.toBluetoothRegisterServiceSuccessCallbackPrivateData(thisObject, arguments[2], errorArgument)); + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + EventBTRegisterRFCOMMEmitterPtr emitter(new EventBTRegisterRFCOMMEmitter); + + if (BluetoothAdapterManager == NULL || emitter == NULL || privData == NULL) + { + LogError("BluetoothAdapterManager or event or listener NULL"); + Throw(UnknownException); + } + LogDebug("UUid:" << uuid << " serviceName:" << serviceName); + + emitter->setListener(&BluetoothAdapterListener::getInstance()); + emitter->setEventPrivateData(DPL::StaticPointerCast(privData)); + serviceSocketFd = BluetoothAdapterManager->registerRFCOMMServiceByUUID(emitter, uuid, serviceName, securityLevel); + + return converter.toJSValueRef(serviceSocketFd); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::UnsupportedException) + { + LogError("NotsupportedException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, "not support error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "unknown error"); + + } + return JSValueMakeUndefined(context); + +} + +JSValueRef JSBluetoothAdapter::unregisterRFCOMMService(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + + LogDebug("unregisterRFCOMMService"); + + JSBluetoothAdapterPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + JSValueRef successCallback = NULL; + JSValueRef errorCallBack = NULL; + + Try + { + + if (priv == NULL) + { + LogError("priv null"); + Throw(UnknownException); + } + + if (argumentCount < 2 || argumentCount > 3) + { + LogError("Wrong parameter count passed"); + Throw(InvalidArgumentException); + } + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADPATER_UNREGISTER_RFCOMM]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + if (JSValueIsNull(context, arguments[0]) == true || JSValueIsNumber(context, arguments[0]) == false) + { + LogError("Wrong parameter passed, type mismatch"); + ThrowMsg(ConversionException, "not a number"); + } + + BluetoothConverter converter(priv->getContext()); + int serviceSocketFd = converter.toInt(arguments[0]); + successCallback = converter.toFunction(arguments[1]); + + if (argumentCount >= 3) + { + errorCallBack = converter.toFunctionOrNull(arguments[2]); + } + + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(priv->getContext(), NULL, NULL); + + if (cbm == NULL) + { + Throw(UnknownException); + } + + cbm->setOnSuccess(successCallback); + cbm->setOnError(errorCallBack); + cbm->setObject(thisObject); + + IBluetoothAdapterManagerPtr BluetoothAdapterManager(priv->getObject()); + EventBTUnregisterRFCOMMServicePtr event(new EventBTUnregisterRFCOMMService); + event->setUnregisterSocket(serviceSocketFd); + + if (BluetoothAdapterManager == NULL || event == NULL) + { + LogError("BluetoothAdapterManager or event or listener NULL"); + Throw(UnknownException); + } + + event->setPrivateData(DPL::StaticPointerCast (cbm)); + BluetoothAdapterListener& listener = BluetoothAdapterListener::getInstance(); + event->setForAsynchronousCall(&listener); + BluetoothAdapterManager->unregisterRFCOMMService(event); + + return JSValueMakeNull(context); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "unknown error"); + + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothAdapter.h b/src/standards/Tizen/Bluetooth/JSBluetoothAdapter.h new file mode 100755 index 0000000..c1faf00 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothAdapter.h @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_TIZEN_JS_BLUETOOTH_ADAPTER_H_ +#define TIZENAPIS_TIZEN_JS_BLUETOOTH_ADAPTER_H_ + +#include +#include +#include + +using namespace TizenApis::Api::Bluetooth; +using namespace WrtDeviceApis::CommonsJavaScript; + + +namespace TizenApis { +namespace Tizen1_0 { + +typedef PrivateObjectT::Type JSBluetoothAdapterPriv; +class JSBluetoothAdapter { +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context); +private: + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception); + + static JSValueRef setPowered( + JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getPowered( + JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + static JSValueRef setVisible( + JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getVisible( + JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + static JSValueRef setName( + JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getName( + JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + + + static JSValueRef discoveryDevices( + JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef stopDiscovery( + JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + + static JSValueRef getKnownDevices( + JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + + static JSValueRef getDevice( + JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + + static JSValueRef createBonding( + JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef destroyBonding( + JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef registerRFCOMMServiceByUUID( + JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unregisterRFCOMMService( + JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getAddress( + JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + static JSClassDefinition m_classInfo; + + static JSStaticFunction m_function[]; + static JSStaticValue m_properties[]; + + static JSClassRef m_jsClassRef; + static bool m_AdapterEnabled; +}; + +} +} + +#endif + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothClass.cpp b/src/standards/Tizen/Bluetooth/JSBluetoothClass.cpp new file mode 100644 index 0000000..03ea433 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothClass.cpp @@ -0,0 +1,305 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "JSBluetoothClass.h" +#include "plugin_config.h" + + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassDefinition JSBluetoothClass::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "BluetoothClass", + NULL, + m_properties, + m_function, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + hasInstance, + NULL +}; + + +JSStaticFunction JSBluetoothClass::m_function[] = +{ + { "hasService", JSBluetoothClass::hasService, kJSPropertyAttributeNone }, + + { 0, 0, 0 } +}; + + +JSStaticValue JSBluetoothClass::m_properties[] = +{ + {"major", JSBluetoothClass::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"minor", JSBluetoothClass::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"services", JSBluetoothClass::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {0, 0, 0, 0} +}; + + +const JSClassRef JSBluetoothClass::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSBluetoothClass::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSBluetoothClass::m_jsClassRef = JSClassCreate(JSBluetoothClass::getClassInfo()); + +void JSBluetoothClass::initialize(JSContextRef context, JSObjectRef object) +{ + LogDebug("JSBluetoothClass::initialize "); + JSBluetoothClassPriv* priv = static_cast(JSObjectGetPrivate(object)); + + if (priv == NULL) + { + BluetoothClassPtr btClass(new BluetoothClass()); + priv = new JSBluetoothClassPriv( context, btClass); + if(!JSObjectSetPrivate(object, static_cast(priv))) + { + LogError("Object can't store private data."); + delete priv; + } + } + else + { + LogDebug("JSBluetoothClass::already exist "); + } +} + + +JSObjectRef JSBluetoothClass::createJSObject(JSContextRef context) +{ + BluetoothClassPtr btClass(new BluetoothClass()); + JSBluetoothClassPriv* priv = new JSBluetoothClassPriv( context, btClass); + btClass->setReadOnly(); + + return JSObjectMake(context, getClassRef(), priv); +} + +JSObjectRef JSBluetoothClass::createJSObject(JSContextRef context, int device) +{ + BluetoothClassPtr btClass(new BluetoothClass()); + JSBluetoothClassPriv* priv = new JSBluetoothClassPriv( context, btClass); + + btClass->fromInt(device); + btClass->setReadOnly(); + + return JSObjectMake(context, getClassRef(), priv); + +} + +JSObjectRef JSBluetoothClass::createJSObject(JSContextRef context, BluetoothDeviceDataClass devClass) +{ + BluetoothClassPtr btClass(new BluetoothClass()); + JSBluetoothClassPriv* priv = new JSBluetoothClassPriv( context, btClass); + + btClass->setMajor(devClass.major); + btClass->setMinor(devClass.minor); + btClass->setServices(devClass.majorServiceMask); + btClass->setReadOnly(); + + LogDebug("Major:" << std::hex << devClass.major << "Minor:" << std::hex << devClass.minor << "ServiceClass:" << devClass.majorServiceMask); + + return JSObjectMake(context, getClassRef(), priv); +} + + +void JSBluetoothClass::finalize(JSObjectRef object) +{ + JSBluetoothClassPriv* priv = static_cast(JSObjectGetPrivate(object)); + + LogDebug("JSBluetoothClass::Finalrize"); + + if (priv != NULL) + { + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +bool JSBluetoothClass::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSBluetoothClass::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("OK"); + + Converter converter(context); + JSBluetoothClassPriv* priv = static_cast(JSObjectGetPrivate(object)); + + try + { + if (priv == NULL) + { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + BluetoothClassPtr btClass(priv->getObject()); + std::string key = converter.toString(propertyName); + int value = 0; + + if (key == "major") + { + value = btClass->getMajor(); + return converter.toJSValueRef(value); + } + else if (key == "minor") + { + value = btClass->getMinor(); + return converter.toJSValueRef(value); + } + else if (key == "services") + { + std::vector service = btClass->getServices(); + JSObjectRef result = JSCreateArrayObject(context, 0, NULL); + + if (!result) + { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Could not create array object."); + } + + for (std::size_t i = 0; i < service.size(); ++i) + { + JSValueRef value = JSValueMakeNumber(context, service[i]); + + if (!JSSetArrayElement(context, result, i, value)) + { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Could not fill array."); + } + } + + return result; + } + else + { + btClass->find(key, value); + return converter.toJSValueRef(value); + } + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("Unkwon Exception"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSBluetoothClass::hasService(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) + +{ + JSBluetoothClassPriv* priv = static_cast(JSObjectGetPrivate(thisObject)); + + try + { + if (priv == NULL) + { + LogError("priv null"); + + Throw(WrtDeviceApis::Commons::UnknownException); + } + + if (argumentCount != 1 || JSValueIsNull(context, arguments[0]) == true + || JSValueIsNumber(context, arguments[0]) == false) + { + LogError("argument fail"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_BLUETOOTHCLASS_HAS_SERVICE]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + BluetoothClassPtr btClass(priv->getObject()); + std::vector service = btClass->getServices(); + Converter converter(context); + int queryService = converter.toInt(arguments[0]); + int index = 0; + + for (index = 0; index < (int)service.size(); index++) + { + if (service[index] == queryService) + { + return converter.toJSValueRef(true); + } + } + return converter.toJSValueRef(false); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch (WrtDeviceApis::Commons::SecurityException) + { + LogError("permission denied error"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::PERMISSION_DENIED_ERROR, "permission denied error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + return JSValueMakeNull(context); +} +} +} + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothClass.h b/src/standards/Tizen/Bluetooth/JSBluetoothClass.h new file mode 100644 index 0000000..c07c7b0 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothClass.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_TIZEN_JS_BLUETOOTH_CLASS_H_ +#define TIZENAPIS_TIZEN_JS_BLUETOOTH_CLASS_H_ + +#include + #include "BluetoothClass.h" +#include + #include + +using namespace TizenApis::Api; +using namespace TizenApis::Api::Bluetooth; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + + +namespace TizenApis { +namespace Tizen1_0 { + + + +typedef PrivateObjectT::Type JSBluetoothClassPriv; + +class JSBluetoothClass { +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, BluetoothDeviceDataClass devClass); + static JSObjectRef createJSObject(JSContextRef context); + static JSObjectRef createJSObject(JSContextRef context, int device); + +private: + static void initialize(JSContextRef context, JSObjectRef object); + static void initConstants(); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception); + + static JSValueRef hasService(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + static JSClassDefinition m_classInfo; + static JSStaticFunction m_function[]; + static JSStaticValue m_properties[]; + + static JSClassRef m_jsClassRef; +}; + +} +} + +#endif + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceMajor.cpp b/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceMajor.cpp new file mode 100644 index 0000000..a211af0 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceMajor.cpp @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "JSBluetoothClassDeviceMajor.h" +#include "plugin_config.h" + + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Commons; + + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassDefinition JSBluetoothClassDeviceMajor::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "BluetoothClassDeviceMajor", + NULL, + m_properties, + NULL, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + hasInstance, + NULL +}; + + + +JSStaticValue JSBluetoothClassDeviceMajor::m_properties[] = +{ + {"MISC", JSBluetoothClassDeviceMajor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"COMPUTER", JSBluetoothClassDeviceMajor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PHONE", JSBluetoothClassDeviceMajor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"NETWORK", JSBluetoothClassDeviceMajor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AUDIO_VIDEO", JSBluetoothClassDeviceMajor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL", JSBluetoothClassDeviceMajor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"IMAGING", JSBluetoothClassDeviceMajor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"WEARABLE", JSBluetoothClassDeviceMajor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"TOY", JSBluetoothClassDeviceMajor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH", JSBluetoothClassDeviceMajor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"UNCATEGORIZED", JSBluetoothClassDeviceMajor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {0, 0, 0, 0} +}; + + +const JSClassRef JSBluetoothClassDeviceMajor::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSBluetoothClassDeviceMajor::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSBluetoothClassDeviceMajor::m_jsClassRef = JSClassCreate(JSBluetoothClassDeviceMajor::getClassInfo()); + +void JSBluetoothClassDeviceMajor::initialize(JSContextRef context, JSObjectRef object) +{ + LogDebug("JSBluetoothClassDeviceMajor::initialize "); + JSBluetoothClassDeviceMajorPriv* priv = static_cast(JSObjectGetPrivate(object)); + + if (priv == NULL) + { + BluetoothClassPtr btClass(new BluetoothClass()); + priv = new JSBluetoothClassDeviceMajorPriv( context, btClass); + if(!JSObjectSetPrivate(object, static_cast(priv))) + { + LogError("Object can't store private data."); + delete priv; + } + } + else + { + LogDebug("JSBluetoothClassDeviceMajor::already exist "); + } +} + + +JSObjectRef JSBluetoothClassDeviceMajor::createJSObject(JSContextRef context) +{ + BluetoothClassPtr btClass(new BluetoothClass()); + JSBluetoothClassDeviceMajorPriv* priv = new JSBluetoothClassDeviceMajorPriv( context, btClass); + btClass->setReadOnly(); + + return JSObjectMake(context, getClassRef(), priv); +} + + +void JSBluetoothClassDeviceMajor::finalize(JSObjectRef object) +{ + JSBluetoothClassDeviceMajorPriv* priv = static_cast(JSObjectGetPrivate(object)); + + LogDebug("JSBluetoothClassDeviceMajor::Finalrize"); + + if (priv != NULL) + { + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +bool JSBluetoothClassDeviceMajor::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSBluetoothClassDeviceMajor::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("OK"); + + JSBluetoothClassDeviceMajorPriv* priv = static_cast(JSObjectGetPrivate(object)); + + try + { + + if (priv == NULL) + { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + Converter converter(context); + BluetoothClassPtr btClass(priv->getObject()); + std::string key = converter.toString(propertyName); + int value = 0; + + if (btClass->find(key, value) == false) + { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, "can not find property" << key); + } + return converter.toJSValueRef(value); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch (WrtDeviceApis::Commons::SecurityException) + { + LogError("permission denied error"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::PERMISSION_DENIED_ERROR, "permission denied error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + return JSValueMakeNull(context); +} +} +} + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceMajor.h b/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceMajor.h new file mode 100644 index 0000000..1f72c3f --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceMajor.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_JS_BLUETOOTH_CLASS_DEVICE_MAJOR_H_ +#define TIZENAPIS_TIZEN_JS_BLUETOOTH_CLASS_DEVICE_MAJOR_H_ + +#include +#include "BluetoothClass.h" +#include +#include + + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSBluetoothClassDeviceMajorPriv; + +class JSBluetoothClassDeviceMajor { +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context); + +private: + static void initialize(JSContextRef context, JSObjectRef object); + static void initConstants(); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + static JSClassDefinition m_classInfo; + static JSStaticValue m_properties[]; + + static JSClassRef m_jsClassRef; +}; + +} +} + +#endif + + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceMinor.cpp b/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceMinor.cpp new file mode 100644 index 0000000..1748072 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceMinor.cpp @@ -0,0 +1,257 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "JSBluetoothClassDeviceMinor.h" +#include "plugin_config.h" + + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Commons; + + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassDefinition JSBluetoothClassDeviceMinor::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "BluetoothClassDeviceMinor", + NULL, + m_properties, + NULL, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + hasInstance, + NULL +}; + + +JSStaticValue JSBluetoothClassDeviceMinor::m_properties[] = +{ + {"COMPUTER_UNCATEGORIZED", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"COMPUTER_DESKTOP", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"COMPUTER_SERVER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"COMPUTER_LAPTOP", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"COMPUTER_HANDHELD_PC_OR_PDA", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"COMPUTER_PALM_PC_OR_PDA", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"COMPUTER_WEARABLE", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PHONE_UNCATEGORIZED", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PHONE_CELLULAR", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PHONE_CORDLESS", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PHONE_SMARTPHONE", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PHONE_MODEM_OR_GATEWAY", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PHONE_ISDN", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_UNRECOGINZED", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_WEARABLE_HEADSET", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_HANDSFREE", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_MICROPHONE", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_LOUDSPEAKER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_HEADPHONES", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_PORTABLE_AUDIO", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_CAR_AUDIO", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_SETTOP_BOX", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_HIFI", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_VCR", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_VIDEO_CAMERA", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_CAMCORDER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_MONITOR", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_DISPLAY_AND_LOUDSPEAKER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_VIDEO_CONFERENCING", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AV_GAMING_TOY", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL_UNCATEGORIZED", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL_KEYBOARD", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL_POINTING_DEVICE", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL_KEYBOARD_AND_POINTING_DEVICE", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL_JOYSTICK", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL_GAMEPAD", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL_REMOTE_CONTROL", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL_SENSING_DEVICE", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL_DEGITIZER_TABLET", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL_CARD_READER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL_DIGITAL_PEN", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL_HANDHELD_SCANNER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"PERIPHERAL_HANDHELD_INPUT_DEVICE", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"IMAGING_UNCATEGORIZED", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"IMAGING_DISPLAY", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"IMAGING_CAMERA", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"IMAGING_SCANNER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"IMAGING_PRINTER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"WEARABLE_WRITST_WATCH", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"WEARABLE_PAGER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"WEARABLE_JACKET", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"WEARABLE_HELMET", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"WEARABLE_GLASSES", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"TOY_ROBOT", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"TOY_VEHICLE", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"TOY_DOLL", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"TOY_CONTROLLER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"TOY_GAME", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_UNDEFINED", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_BLOOD_PRESSURE_MONITOR", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_THERMOMETER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_WEIGHING_SCALE", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_GLUCOSE_METER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_PULSE_OXIMETER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_PULSE_RATE_MONITOR", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_DATA_DISPLAY", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_STEP_COUNTER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_BODY_COMPOSITION_ANALYZER", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_PEAK_FLOW_MONITOR", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_MEDICATION_MONITOR", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_KNEE_PROSTHESIS", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"HEALTH_ANKLE_PROSTHESIS", JSBluetoothClassDeviceMinor::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {0, 0, 0, 0} +}; + + +const JSClassRef JSBluetoothClassDeviceMinor::getClassRef() +{ + if (!m_jsClassRef) + { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSBluetoothClassDeviceMinor::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSBluetoothClassDeviceMinor::m_jsClassRef = JSClassCreate(JSBluetoothClassDeviceMinor::getClassInfo()); + +void JSBluetoothClassDeviceMinor::initialize(JSContextRef context, JSObjectRef object) +{ + LogDebug("JSBluetoothClassDeviceMinor::initialize "); + JSBluetoothClassDeviceMinorPriv* priv = static_cast(JSObjectGetPrivate(object)); + + if (priv == NULL) + { + BluetoothClassPtr btClass(new BluetoothClass()); + priv = new JSBluetoothClassDeviceMinorPriv( context, btClass); + if(!JSObjectSetPrivate(object, static_cast(priv))) + { + LogError("Object can't store private data."); + delete priv; + } + } + else + { + LogDebug("JSBluetoothClassDeviceMinor::already exist "); + } +} + + +JSObjectRef JSBluetoothClassDeviceMinor::createJSObject(JSContextRef context) +{ + BluetoothClassPtr btClass(new BluetoothClass()); + JSBluetoothClassDeviceMinorPriv* priv = new JSBluetoothClassDeviceMinorPriv( context, btClass); + btClass->setReadOnly(); + + return JSObjectMake(context, getClassRef(), priv); +} + + +void JSBluetoothClassDeviceMinor::finalize(JSObjectRef object) +{ + JSBluetoothClassDeviceMinorPriv* priv = static_cast(JSObjectGetPrivate(object)); + + LogDebug("JSBluetoothClassDeviceMinor::Finalrize"); + + if (priv != NULL) + { + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +bool JSBluetoothClassDeviceMinor::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSBluetoothClassDeviceMinor::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("OK"); + + Converter converter(context); + JSBluetoothClassDeviceMinorPriv* priv = static_cast(JSObjectGetPrivate(object)); + + try + { + if (priv == NULL) + { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + Converter converter(context); + BluetoothClassPtr btClass(priv->getObject()); + std::string key = converter.toString(propertyName); + int value = 0; + + if (btClass->find(key, value) == false) + { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, "can not find property" << key); + } + return converter.toJSValueRef(value); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch (WrtDeviceApis::Commons::SecurityException) + { + LogError("permission denied error"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::PERMISSION_DENIED_ERROR, "permission denied error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + + return JSValueMakeNull(context); +} +} +} + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceMinor.h b/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceMinor.h new file mode 100644 index 0000000..251f3f4 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceMinor.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** +* @file JSBluetoothClassDeviceMinor.h +* @author Kangsoo Lee (wpeter.lee@samsung.com) +* @version 0.1 +*/ + +#ifndef TIZENAPIS_TIZEN_JS_BLUETOOTH_CLASS_H_ +#define TIZENAPIS_TIZEN_JS_BLUETOOTH_CLASS_H_ + +#include + #include "BluetoothClass.h" +#include + #include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSBluetoothClassDeviceMinorPriv; + +class JSBluetoothClassDeviceMinor +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context); + +private: + static void initialize(JSContextRef context, JSObjectRef object); + static void initConstants(); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + static JSClassDefinition m_classInfo; + static JSStaticValue m_properties[]; + + static JSClassRef m_jsClassRef; +}; + +} +} + +#endif + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceService.cpp b/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceService.cpp new file mode 100644 index 0000000..5850885 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceService.cpp @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include "JSBluetoothClassDeviceService.h" +#include "plugin_config.h" + + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Commons; + + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassDefinition JSBluetoothClassDeviceService::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "BluetoothClassDeviceService", + NULL, + m_properties, + NULL, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + hasInstance, + NULL +}; + + + +JSStaticValue JSBluetoothClassDeviceService::m_properties[] = +{ + {"LIMITED_DISCOVERABILITY", JSBluetoothClassDeviceService::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"POSITIONING", JSBluetoothClassDeviceService::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"NETWORKING", JSBluetoothClassDeviceService::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"RENDERING", JSBluetoothClassDeviceService::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"CAPTURING", JSBluetoothClassDeviceService::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"OBJECT_TRANSFER", JSBluetoothClassDeviceService::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"AUDIO", JSBluetoothClassDeviceService::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"TELEPHONY", JSBluetoothClassDeviceService::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"INFORMATION", JSBluetoothClassDeviceService::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {0, 0, 0, 0} +}; + + +const JSClassRef JSBluetoothClassDeviceService::getClassRef() +{ + if (!m_jsClassRef) + { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSBluetoothClassDeviceService::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSBluetoothClassDeviceService::m_jsClassRef = JSClassCreate(JSBluetoothClassDeviceService::getClassInfo()); + +void JSBluetoothClassDeviceService::initialize(JSContextRef context, JSObjectRef object) +{ + LogDebug("JSBluetoothClassDeviceService::initialize "); + JSBluetoothClassDeviceServicePriv* priv = static_cast(JSObjectGetPrivate(object)); + + if (priv == NULL) + { + BluetoothClassPtr btClass(new BluetoothClass()); + priv = new JSBluetoothClassDeviceServicePriv( context, btClass); + if(!JSObjectSetPrivate(object, static_cast(priv))) + { + LogError("Object can't store private data."); + delete priv; + } + } + else + { + LogDebug("JSBluetoothClassDeviceService::already exist "); + } +} + + +JSObjectRef JSBluetoothClassDeviceService::createJSObject(JSContextRef context) +{ + BluetoothClassPtr btClass(new BluetoothClass()); + JSBluetoothClassDeviceServicePriv* priv = new JSBluetoothClassDeviceServicePriv( context, btClass); + btClass->setReadOnly(); + + return JSObjectMake(context, getClassRef(), priv); +} + +void JSBluetoothClassDeviceService::finalize(JSObjectRef object) +{ + JSBluetoothClassDeviceServicePriv* priv = static_cast(JSObjectGetPrivate(object)); + + LogDebug("JSBluetoothClassDeviceService::Finalrize"); + + if (priv != NULL) + { + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +bool JSBluetoothClassDeviceService::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSBluetoothClassDeviceService::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("OK"); + + Converter converter(context); + JSBluetoothClassDeviceServicePriv* priv = static_cast(JSObjectGetPrivate(object)); + + try + { + if (priv == NULL) + { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + BluetoothClassPtr btClass(priv->getObject()); + std::string key = converter.toString(propertyName); + int value = 0; + + if (btClass->find(key, value) == false) + { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, "can not find property" << key); + } + return converter.toJSValueRef(value); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch (WrtDeviceApis::Commons::SecurityException) + { + LogError("permission denied error"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::PERMISSION_DENIED_ERROR, "permission denied error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + + return JSValueMakeNull(context); +} +} +} + + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceService.h b/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceService.h new file mode 100644 index 0000000..258030e --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothClassDeviceService.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_JS_BLUETOOTH_CLASS_DEVICE_SERVICE_H_ +#define TIZENAPIS_TIZEN_JS_BLUETOOTH_CLASS_DEVICE_SERVICE_H_ + +#include +#include "BluetoothClass.h" +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSBluetoothClassDeviceServicePriv; + +class JSBluetoothClassDeviceService +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context); + + +private: + static void initialize(JSContextRef context, JSObjectRef object); + static void initConstants(); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception); + + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + static JSClassDefinition m_classInfo; + static JSStaticValue m_properties[]; + static JSClassRef m_jsClassRef; +}; +} +} + +#endif + + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothDevice.cpp b/src/standards/Tizen/Bluetooth/JSBluetoothDevice.cpp new file mode 100755 index 0000000..773d178 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothDevice.cpp @@ -0,0 +1,627 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "JSBluetoothDevice.h" +#include +#include +#include "BluetoothDeviceManagerListener.h" +#include +#include "JSBluetoothClass.h" +#include "BluetoothConverter.h" +#include "plugin_config.h" + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis; +using namespace TizenApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { + + +JSClassDefinition JSBluetoothDevice::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "BluetoothDevice", + NULL, + m_properties, + m_function, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + hasInstance, + NULL +}; + +JSStaticFunction JSBluetoothDevice::m_function[] = +{ + { "connectToServiceByUUID", JSBluetoothDevice::connectToServiceByUUID, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSStaticValue JSBluetoothDevice::m_properties[] = { + {"name", getName, NULL, kJSPropertyAttributeReadOnly}, + {"address", getAddress, NULL, kJSPropertyAttributeReadOnly}, + {"deviceClass", getDeviceClass, NULL, kJSPropertyAttributeReadOnly}, + {"isBonded", getBondProperty, NULL, kJSPropertyAttributeReadOnly}, + {"isTrusted", getTrustProperty, NULL, kJSPropertyAttributeReadOnly}, + {"isConnected", getConnectProperty, NULL, kJSPropertyAttributeReadOnly}, + {"uuids", getUuids, NULL, kJSPropertyAttributeReadOnly}, + {0, 0, 0, 0} +}; + +const JSClassRef JSBluetoothDevice::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSBluetoothDevice::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSBluetoothDevice::m_jsClassRef = JSClassCreate(JSBluetoothDevice::getClassInfo()); + +void JSBluetoothDevice::initialize(JSContextRef context, JSObjectRef object) +{ + LogDebug("initialize "); + + JSBluetoothDevicePriv *priv = static_cast(JSObjectGetPrivate(object)); + + if (priv == NULL) + { + IBluetoothDeviceManagerPtr BluetoothManager(BluetoothFactory::getInstance().getBluetoothDeviceManager()); + priv = new JSBluetoothDevicePriv( context, BluetoothManager); + + if(!JSObjectSetPrivate(object, static_cast(priv))) + { + LogError("Object can't store private data."); + delete priv; + } + } + else + { + LogDebug("already exist"); + } + + +} + +void JSBluetoothDevice::finalize(JSObjectRef object) +{ + LogDebug("Finalrize"); + + JSBluetoothDevicePriv* priv = static_cast(JSObjectGetPrivate(object)); + + if (priv != NULL) + { + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting BluetoothManager"); + delete priv; + } +} + + +bool JSBluetoothDevice::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + + +JSObjectRef JSBluetoothDevice::createJSObject(JSContextRef context, BluetoothDeviceData device) +{ + IBluetoothDeviceManagerPtr BluetoothManager(BluetoothFactory::getInstance().getBluetoothDeviceManager()); + BluetoothManager->setDevice(device); + + JSBluetoothDevicePriv* priv = new JSBluetoothDevicePriv( context, BluetoothManager); + return JSObjectMake(context, getClassRef(), priv); +} + + + +JSValueRef JSBluetoothDevice::getName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + + Converter converter(context); + JSBluetoothDevicePriv *priv = static_cast(JSObjectGetPrivate(object)); + + Try + { + if (priv == NULL) + { + Throw(UnknownException); + } + + IBluetoothDeviceManagerPtr BluetoothDeviceManager(priv->getObject()); + std::string name = BluetoothDeviceManager->getNameProperty(); + LogDebug("name" << name); + return converter.toJSValueRef(name); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("WrtDeviceApis::Commons::ConversionException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("hasInstance Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSBluetoothDevice::getAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + + Converter converter(context); + JSBluetoothDevicePriv *priv = static_cast(JSObjectGetPrivate(object)); + + Try + { + if (priv == NULL) + { + Throw(UnknownException); + } + + IBluetoothDeviceManagerPtr BluetoothDeviceManager(priv->getObject()); + std::string address = BluetoothDeviceManager->getAddressProperty(); + + LogDebug("address" << address); + return converter.toJSValueRef(address); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversationException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("hasInstance Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + return JSValueMakeUndefined(context); +} +JSValueRef JSBluetoothDevice::getDeviceClass(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + + JSBluetoothDevicePriv *priv = static_cast(JSObjectGetPrivate(object)); + + Try + { + if (priv == NULL) + { + Throw(UnknownException); + } + IBluetoothDeviceManagerPtr BluetoothDeviceManager(priv->getObject()); + BluetoothDeviceDataClass devClass = BluetoothDeviceManager->getClass(); + + LogDebug("Major:" << std::hex << devClass.major << "Minor:" << std::hex << devClass.minor << "Service Mask:" << std::hex << devClass.majorServiceMask); + + JSObjectRef adapterObject = JSBluetoothClass::createJSObject(priv->getContext(), devClass); + return adapterObject; + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversationException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("hasInstance Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + return JSValueMakeUndefined(context); + +} +JSValueRef JSBluetoothDevice::getBondProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + + Converter converter(context); + JSBluetoothDevicePriv *priv = static_cast(JSObjectGetPrivate(object)); + + Try + { + if (priv == NULL) + { + Throw(UnknownException); + } + + IBluetoothDeviceManagerPtr BluetoothDeviceManager(priv->getObject()); + bool isBonded = BluetoothDeviceManager->getBondProperty(); + + LogDebug("isBonded " << isBonded); + + return converter.toJSValueRef(isBonded); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversationException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::INVALID_VALUES_ERROR, "invalid value error");; + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("hasInstance Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + return JSValueMakeUndefined(context); +} +JSValueRef JSBluetoothDevice::getTrustProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + + Converter converter(context); + JSBluetoothDevicePriv *priv = static_cast(JSObjectGetPrivate(object)); + + Try + { + if (priv == NULL) + { + Throw(UnknownException); + } + + IBluetoothDeviceManagerPtr BluetoothDeviceManager(priv->getObject()); + bool isTrusted = BluetoothDeviceManager->getTrustProperty(); + + LogDebug("isTrusted " << isTrusted); + return converter.toJSValueRef(isTrusted); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversationException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::INVALID_VALUES_ERROR, "invalid value error");; + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("hasInstance Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + return JSValueMakeUndefined(context); +} +JSValueRef JSBluetoothDevice::getConnectProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + + Converter converter(context); + JSBluetoothDevicePriv *priv = static_cast(JSObjectGetPrivate(object)); + + Try + { + if (priv == NULL) + { + Throw(UnknownException); + } + IBluetoothDeviceManagerPtr BluetoothDeviceManager(priv->getObject()); + bool isConnected = BluetoothDeviceManager->getConnectProperty(); + + LogDebug("isConnected " << isConnected); + return converter.toJSValueRef(isConnected); + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversationException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::INVALID_VALUES_ERROR, "invalid value error");; + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("hasInstance Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + return JSValueMakeUndefined(context); + +} + +JSValueRef JSBluetoothDevice::getUuids(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Enter"); + + Converter converter(context); + JSBluetoothDevicePriv *priv = static_cast(JSObjectGetPrivate(object)); + + Try + { + if (priv == NULL) + { + Throw(UnknownException); + } + + IBluetoothDeviceManagerPtr BluetoothDeviceManager(priv->getObject()); + std::vector uuids = BluetoothDeviceManager->getUuidsProperty(); + JSObjectRef result = JSCreateArrayObject(context, 0, NULL); + int length = uuids.size(); + + if (!result) + { + return converter.toJSValueRef(""); + } + + for (int i = 0; i < length; ++i) + { + JSValueRef value = converter.toJSValueRef(uuids[i]); + + if (!JSSetArrayElement(context, result, i, value)) + { + return converter.toJSValueRef(""); + } + } + + return result; + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversationException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::INVALID_VALUES_ERROR, "invalid value error");; + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("hasInstance Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + return JSValueMakeUndefined(context); + +} + + + + +JSValueRef JSBluetoothDevice::connectToServiceByUUID(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) { + + LogDebug("connectToServiceByUUID"); + + JSBluetoothDevicePriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + JSValueRef successCallback = NULL; + JSValueRef errorCallBack = NULL; + + + Try { + + + if (priv == NULL) + { + LogError("priv null"); + Throw(UnknownException); + } + + LogDebug(bluetoothExportedNames[BLUETOOTH_FUNCTION_API_DEVICE_CONNECT_TO_SERVICE]); + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_DEVICE_CONNECT_TO_SERVICE]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount < 2 || argumentCount > 4) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + if (JSValueIsNull(context, arguments[0]) == true || JSValueIsString(context, arguments[0]) == false) + { + LogError("hasInstance TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + } + + BluetoothConverter converter(context); + successCallback = converter.toFunction(arguments[1]); + + if (argumentCount >= 3) + { + errorCallBack = converter.toFunctionOrNull(arguments[2]); + } + + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(priv->getContext(), NULL, NULL); + + if (cbm == NULL) + { + return JSValueMakeUndefined(context); + } + cbm->setOnSuccess(successCallback); + cbm->setOnError(errorCallBack); + cbm->setObject(thisObject); + + IBluetoothDeviceManagerPtr BluetoothDeviceManager(priv->getObject()); + EventBTConnectToServiceByUUIDPtr event(new EventBTConnectToServiceByUUID); + BluetoothSocketData socketData; + socketData.uuid = converter.toString(arguments[0]); + socketData.protocol = PROTOCOL_TYPE_RFCOMM_VALUE_INT; + + if (argumentCount >= 4) + { + if (JSValueIsNull(context, arguments[3]) == true) + { + socketData.protocol = PROTOCOL_TYPE_RFCOMM_VALUE_INT; + } + else + { + if (JSValueIsString(context, arguments[3]) == false) + { + + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, + exception, JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + } + + std::string protocol = converter.toString(arguments[3]); + LogDebug(protocol.c_str()); + + if (strcmp(protocol.c_str(), PROTOCOL_TYPE_RFCOMM_VALUE) == 0) + { + socketData.protocol = PROTOCOL_TYPE_RFCOMM_VALUE_INT; + } + else + { + LogError("BluetoothDeviceManager or event or listener NULL"); + Throw(WrtDeviceApis::Commons::UnsupportedException); + } + + } + } + + if (BluetoothDeviceManager == NULL || event == NULL) + { + LogError("BluetoothDeviceManager or event or listener NULL"); + Throw(WrtDeviceApis::Commons::UnknownException); + } + + event->setPrivateData(DPL::StaticPointerCast (cbm)); + + event->setForAsynchronousCall(&BluetoothDeviceManagerListener::getInstance()); + event->setSocketData(socketData); + BluetoothDeviceManager->connectToServiceByUUID(event); + + return JSValueMakeNull(context); + } + + Catch (WrtDeviceApis::Commons::UnsupportedException) + { + LogError("UnsupportedException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, "not support error"); + + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LogError("Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "unknown error"); + + } + + return JSValueMakeUndefined(context); +} + + +} +} + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothDevice.h b/src/standards/Tizen/Bluetooth/JSBluetoothDevice.h new file mode 100644 index 0000000..c4f33dc --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothDevice.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_TIZEN_JS_BLUETOOTH_DEVICE_H_ +#define TIZENAPIS_TIZEN_JS_BLUETOOTH_DEVICE_H_ + +#include +#include +#include + +using namespace TizenApis::Api; +using namespace TizenApis::Api::Bluetooth; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +typedef PrivateObjectT::Type JSBluetoothDevicePriv; + +class JSBluetoothDevice +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, BluetoothDeviceData device); + + +private: + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception); + static JSValueRef getName(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static JSValueRef getAddress(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static JSValueRef getDeviceClass(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static JSValueRef getBondProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static JSValueRef getTrustProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static JSValueRef getConnectProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static JSValueRef getUuids(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static JSValueRef connectToServiceByUUID(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + static JSClassDefinition m_classInfo; + static JSStaticFunction m_function[]; + static JSStaticValue m_properties[]; + static JSClassRef m_jsClassRef; +}; + +} +} + +#endif + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothManager.cpp b/src/standards/Tizen/Bluetooth/JSBluetoothManager.cpp new file mode 100755 index 0000000..00a3e78 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothManager.cpp @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include "JSBluetoothManager.h" +#include "JSBluetoothClassDeviceMajor.h" +#include "JSBluetoothClassDeviceMinor.h" +#include "JSBluetoothClassDeviceService.h" + + +using namespace TizenApis::Api::Bluetooth; +using namespace WrtDeviceApis::Commons; +using namespace TizenApis::Commons; + + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassRef JSBluetoothManager::m_jsClassRef = NULL; + +JSClassDefinition JSBluetoothManager::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "BluetoothManager", + NULL, + m_properties, + NULL, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + + + + +JSStaticValue JSBluetoothManager::m_properties[] = +{ +/* {PROTOCOL_TYPE_RFCOMM, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {PROTOCOL_TYPE_L2CAP, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {SECURITY_LEVEL_LOW, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {SECURITY_LEVEL_MEDIUM, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {SECURITY_LEVEL_HIGH, getProperty, NULL, kJSPropertyAttributeReadOnly},*/ + {"DeviceMajor", getProperty, NULL, kJSPropertyAttributeReadOnly}, + {"DeviceMinor", getProperty, NULL, kJSPropertyAttributeReadOnly}, + {"DeviceService", getProperty, NULL, kJSPropertyAttributeReadOnly}, + {0, 0, 0, 0} +}; + + + +const JSClassRef JSBluetoothManager::getClassRef() +{ + if (!m_jsClassRef) + { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + + +void JSBluetoothManager::getPropertyNames(JSContextRef context, + JSObjectRef object, + JSPropertyNameAccumulatorRef propertyNames) +{ +} + + +JSValueRef JSBluetoothManager::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("OK"); + + try + { + /* + if(JSStringIsEqualToUTF8CString(propertyName, PROTOCOL_TYPE_RFCOMM)) + { + return converter.toJSValueRef(PROTOCOL_TYPE_RFCOMM_VALUE); + } + else if(JSStringIsEqualToUTF8CString(propertyName, PROTOCOL_TYPE_L2CAP)) + { + return converter.toJSValueRef(PROTOCOL_TYPE_L2CAP_VALUE); + } + else if(JSStringIsEqualToUTF8CString(propertyName, SECURITY_LEVEL_LOW)) + { + return converter.toJSValueRef(SECURITY_LEVEL_LOW_VALUE); + } + else if(JSStringIsEqualToUTF8CString(propertyName, SECURITY_LEVEL_MEDIUM)) + { + return converter.toJSValueRef(SECURITY_LEVEL_MEDIUM_VALUE); + } + else if(JSStringIsEqualToUTF8CString(propertyName, SECURITY_LEVEL_HIGH)) + { + return converter.toJSValueRef(SECURITY_LEVEL_HIGH_VALUE); + } + else*/ if(JSStringIsEqualToUTF8CString(propertyName, "DeviceMajor")) + { + return JSBluetoothClassDeviceMajor::createJSObject(context); + } + else if(JSStringIsEqualToUTF8CString(propertyName, "DeviceMinor")) + { + return JSBluetoothClassDeviceMinor::createJSObject(context); + } + else if(JSStringIsEqualToUTF8CString(propertyName, "DeviceService")) + { + return JSBluetoothClassDeviceService::createJSObject(context); + } + + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + return JSValueMakeUndefined(context); +} + + + +const JSClassDefinition* JSBluetoothManager::getClassInfo() +{ + return &m_classInfo; +} + + +void JSBluetoothManager::initialize(JSContextRef context, JSObjectRef object) +{ + JSBluetoothManagerPriv *priv = static_cast(JSObjectGetPrivate(object)); + LogDebug("JSBluetoothManager::initialize"); + + if (priv != NULL) + { + LogError("already exist"); + } + else + { + priv = new JSBluetoothManagerPriv(context); + + if(!JSObjectSetPrivate(object, static_cast(priv))) + { + LogError("Object can't store private data."); + delete priv; + } + } +} + +void JSBluetoothManager::finalize(JSObjectRef object) +{ + JSBluetoothManagerPriv* priv = static_cast(JSObjectGetPrivate(object)); + LogDebug("JSBluetoothManager::Finalrize"); + + if (priv != NULL) + { + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting BluetoothManager"); + delete priv; + } +} + +bool JSBluetoothManager::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} +} +} + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothManager.h b/src/standards/Tizen/Bluetooth/JSBluetoothManager.h new file mode 100644 index 0000000..aad79e4 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothManager.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_TIZEN_JS_BLUETOOTH_H_ +#define TIZENAPIS_TIZEN_JS_BLUETOOTH_H_ + +#include + #include + +using namespace WrtDeviceApis; + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSBluetoothManagerPriv; + +class JSBluetoothManager +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + +private: + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static void getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames); + static JSClassDefinition m_classInfo; + static JSStaticValue m_properties[]; + static JSClassRef m_jsClassRef; +}; +} +} + +#endif + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothSocket.cpp b/src/standards/Tizen/Bluetooth/JSBluetoothSocket.cpp new file mode 100755 index 0000000..bf154f2 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothSocket.cpp @@ -0,0 +1,517 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "BluetoothSocketListener.h" +#include "JSBluetoothSocket.h" +#include "JSBluetoothDevice.h" +#include "BluetoothMultiCallback.h" +#include "BluetoothConverter.h" +#include +#include "plugin_config.h" + +using namespace std; +using namespace DPL; +using namespace TizenApis::Api; +using namespace TizenApis::Api::Bluetooth; +using namespace TizenApis::Commons; + + +namespace TizenApis { +namespace Tizen1_0 { + + +JSClassDefinition JSBluetoothSocket::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "BluetoothSocket", + NULL, + m_properties, + m_function, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + hasInstance, + NULL +}; + +JSStaticValue JSBluetoothSocket::m_properties[] = +{ + {"uuid", getProperty, NULL, kJSPropertyAttributeReadOnly}, + {"protocol", getProperty, NULL, kJSPropertyAttributeReadOnly}, + {"state", getProperty, NULL, kJSPropertyAttributeReadOnly}, + {"peer", getProperty, NULL, kJSPropertyAttributeReadOnly}, + {0, 0, 0, 0} +}; + + +JSStaticFunction JSBluetoothSocket::m_function[] = +{ + { "setSocketNotifyListener", JSBluetoothSocket::setSocketNotifier, kJSPropertyAttributeNone }, + { "writeData", JSBluetoothSocket::writeData, kJSPropertyAttributeNone }, + { "readData", JSBluetoothSocket::readData, kJSPropertyAttributeNone }, + { "close", JSBluetoothSocket::close, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef JSBluetoothSocket::getClassRef() +{ + if (!m_jsClassRef) + { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSBluetoothSocket::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSBluetoothSocket::m_jsClassRef = JSClassCreate(JSBluetoothSocket::getClassInfo()); + +void JSBluetoothSocket::initialize(JSContextRef context, JSObjectRef object) +{ + LogDebug("JSBluetoothSocket::initialize "); + +} + +void JSBluetoothSocket::finalize(JSObjectRef object) +{ + LogDebug("JSBluetoothSocket::Finalrize"); + + JSBluetoothSocketPriv *priv = static_cast(JSObjectGetPrivate(object)); + + if (priv != NULL) + { + delete priv; + JSObjectSetPrivate(object, NULL); + } +} + +bool JSBluetoothSocket::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSObjectRef JSBluetoothSocket::createJSObject(JSContextRef context, BluetoothSocketData socketData) +{ + IBluetoothSocketManagerPtr BluetoothSocketManager(BluetoothFactory::getInstance().getBluetoothSocketManager()); + JSBluetoothSocketPriv* priv = new JSBluetoothSocketPriv( context, BluetoothSocketManager); + BluetoothSocketManager->setSocketData(socketData); + return JSObjectMake(context, getClassRef(), priv); +} + +JSObjectRef JSBluetoothSocket::createJSObject(JSContextRef context, BluetoothSocketData socketData, EventBTReadDataType readData) +{ + IBluetoothSocketManagerPtr BluetoothSocketManager(BluetoothFactory::getInstance().getBluetoothSocketManager()); + JSBluetoothSocketPriv* priv = new JSBluetoothSocketPriv( context, BluetoothSocketManager); + BluetoothSocketManager->setSocketData(socketData); + BluetoothSocketManager->setReadData(readData); + return JSObjectMake(context, getClassRef(), priv); +} +JSValueRef JSBluetoothSocket::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("OK"); + + + try + { + JSBluetoothSocketPriv *priv = static_cast(JSObjectGetPrivate(object)); + IBluetoothSocketManagerPtr BluetoothSocketManager(priv->getObject()); + BluetoothConverter converter(priv->getContext()); + + if (priv == NULL) + { + LogError("priv null"); + Throw(WrtDeviceApis::Commons::UnknownException); + } + + if(JSStringIsEqualToUTF8CString(propertyName, "uuid")) + { + std::string uuid = BluetoothSocketManager->getUUID(); + return converter.toJSValueRef(uuid); + } + else if(JSStringIsEqualToUTF8CString(propertyName, "protocol")) + { + unsigned short int protocol = BluetoothSocketManager->getProtocol(); + return converter.toBluetoothProtocolJSValue(protocol); + + } + else if(JSStringIsEqualToUTF8CString(propertyName, "state")) + { + unsigned short int state = BluetoothSocketManager->getState(); + return converter.toBluetoothStateJSValue(state); + } + else if(JSStringIsEqualToUTF8CString(propertyName, "peer")) + { + BluetoothDeviceData device = BluetoothSocketManager->getPeer(); + JSObjectRef adapterObject = JSBluetoothDevice::createJSObject(priv->getContext(), device); + return adapterObject; + } + } + + Catch (WrtDeviceApis::Commons::SecurityException) + { + LogError("permission denied error"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::PERMISSION_DENIED_ERROR, "permission denied error"); + + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch (WrtDeviceApis::Commons::UnknownException) + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + + return JSValueMakeUndefined(context); +} + + + +JSValueRef JSBluetoothSocket::setSocketNotifier(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + + LogDebug("JSBluetoothSocket"); + + Try + { + JSBluetoothSocketPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + + if (priv == NULL) + { + LogError("priv null"); + Throw(WrtDeviceApis::Commons::UnknownException); + } + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_SOCKET_SET_SOCKETNOTIFIER]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount < 1) + { + LogError("Wrong parameter passed"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + BluetoothConverter converter(priv->getContext()); + + BluetoothSocketNotifierPrivateDataPtr privData( + converter.toBluetoothSocketNotifierPrivateData(thisObject, arguments[0])); + + IBluetoothSocketManagerPtr BluetoothSocketManager(priv->getObject()); + EventBTSocketNotificationEmitterPtr emitter(new EventBTSocketNotificationEmitter); + + if (BluetoothSocketManager == NULL || emitter == NULL || privData == NULL) + { + LogError("BluetoothManager or event or listener NULL"); + Throw(WrtDeviceApis::Commons::UnknownException); + } + emitter->setListener(&BluetoothSocketListener::getInstance()); + emitter->setEventPrivateData(DPL::StaticPointerCast(privData)); + + if (BluetoothSocketManager->setSocketNotifier(emitter) != BT_ERROR_NONE) + { + LogError("callback set error"); + Throw(WrtDeviceApis::Commons::UnknownException); + } + + return JSValueMakeNull(context); + } + Catch (WrtDeviceApis::Commons::SecurityException) + { + LogError("permission denied error"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::PERMISSION_DENIED_ERROR, "permission denied error"); + + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch (WrtDeviceApis::Commons::UnknownException) + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + + return JSValueMakeUndefined(context); + +} + +JSValueRef JSBluetoothSocket::writeData(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("JSBluetoothSocket"); + Converter converter(context); + Try + { + JSBluetoothSocketPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + + if (priv == NULL) + { + LogError("priv null"); + Throw(WrtDeviceApis::Commons::UnknownException); + } + + if (argumentCount < 1 || JSValueIsNull(context, arguments[0]) == true) + { + LogError("argument wrong"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_SOCKET_WRITE_DATA]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + IBluetoothSocketManagerPtr BluetoothSocketManager(priv->getObject()); + std::vector data = converter.toVectorOfChars(arguments[0]); + unsigned int index = 0; + + if (data.size() == 0) + { + LogError("size 0 array passed"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + DPL::ScopedArray buffer(new char[data.size()]); + + for (index = 0; index < data.size(); index++) + { + buffer[index] = data[index]; + } + + if (BluetoothSocketManager->writeData(buffer.Get(), data.size()) != BT_ERROR_NONE) + { + LogError("BluetoothSocket Write Error"); + Throw(WrtDeviceApis::Commons::UnknownException); + } + + return converter.toJSValueRef(data.size()); + } + Catch (WrtDeviceApis::Commons::SecurityException) + { + LogError("permission denied error"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::PERMISSION_DENIED_ERROR, "permission denied error"); + + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch (WrtDeviceApis::Commons::UnknownException) + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + + return converter.toJSValueRef(0); +} + + +JSValueRef JSBluetoothSocket::readData(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + + + LogDebug("JSBluetoothSocket"); + + Try + { + JSBluetoothSocketPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + + IBluetoothSocketManagerPtr BluetoothSocketManager(priv->getObject()); + EventBTReadDataType data = BluetoothSocketManager->readData(); + int length = data.size(); + BluetoothConverter converter(priv->getContext()); + + if (length == 0) + { + LogError("BluetoothSocket Read Error"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_SOCKET_READ_DATA]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + JSObjectRef result = converter.toBluetoothByteArray(data); + return result; + } + Catch (WrtDeviceApis::Commons::SecurityException) + { + LogError("permission denied error"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::PERMISSION_DENIED_ERROR, "permission denied error"); + + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + + return JSValueMakeUndefined(context); +} + + +JSValueRef JSBluetoothSocket::close(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("JSBluetoothSocket"); + + Try + { + JSBluetoothSocketPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + + IBluetoothSocketManagerPtr BluetoothSocketManager(priv->getObject()); + + LogDebug(bluetoothExportedNames[BLUETOOTH_FUNCTION_API_SOCKET_CLOSE]); + + AceSecurityStatus status = BLUETOOTH_CHECK_ACCESS( + priv->getContext(), + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_SOCKET_CLOSE]); + + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + } + Catch (WrtDeviceApis::Commons::SecurityException) + { + LogError("permission denied error"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::PERMISSION_DENIED_ERROR, "permission denied error"); + + } + Catch (WrtDeviceApis::Commons::ConversionException) + { + LogError("ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter error"); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("UnkownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, "Unkown error"); + } + + + return JSValueMakeUndefined(context); + +} +} +} + diff --git a/src/standards/Tizen/Bluetooth/JSBluetoothSocket.h b/src/standards/Tizen/Bluetooth/JSBluetoothSocket.h new file mode 100644 index 0000000..3223bba --- /dev/null +++ b/src/standards/Tizen/Bluetooth/JSBluetoothSocket.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_JS_BLUETOOTH_SOCKET_H_ +#define TIZENAPIS_TIZEN_JS_BLUETOOTH_SOCKET_H_ + +#include +#include +#include +#include + +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +typedef PrivateObjectT::Type JSBluetoothSocketPriv; +class JSBluetoothSocket +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, BluetoothSocketData socketData); + static JSObjectRef createJSObject(JSContextRef context, BluetoothSocketData socketData, + EventBTReadDataType readData); + +private: + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception); + + static JSValueRef setSocketNotifier(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef writeData(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + + static JSValueRef readData(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + + static JSValueRef close(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSClassDefinition m_classInfo; + static JSStaticFunction m_function[]; + static JSStaticValue m_properties[]; + + static JSClassRef m_jsClassRef; + +}; + +} +} + +#endif + diff --git a/src/standards/Tizen/Bluetooth/config.xml b/src/standards/Tizen/Bluetooth/config.xml new file mode 100644 index 0000000..d44963c --- /dev/null +++ b/src/standards/Tizen/Bluetooth/config.xml @@ -0,0 +1,75 @@ + + + + libwrt-plugins-tizen-1.0-bluetooth.so + bluetooth.install.uri + SAMSUNG plugin group + SAMSUNG certificate authority + AAAABBBBCCCCDDDEEEE0000 + + + http://tizen.org/api/bluetooth + bluetooth + + + + + http://tizen.org/api/bluetooth + + + + + + + + + + + + + + + + + + + + + + + + + + + http://tizen.org/api/bluetooth.gap + bluetooth.gap + + + + + + + + + + + + + + http://tizen.org/api/bluetooth.spp + bluetooth.spp + + + + + + + + + + + + + + + diff --git a/src/standards/Tizen/Bluetooth/plugin_config.cpp b/src/standards/Tizen/Bluetooth/plugin_config.cpp new file mode 100755 index 0000000..747f7b4 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/plugin_config.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include "plugin_config.h" + +#define BLUETOOTH_FEATURE_API "http://tizen.org/api/bluetooth" +#define BLUETOOTH_FEATURE_API_GAP "http://tizen.org/api/bluetooth.gap" +#define BLUETOOTH_FEATURE_API_SPP "http://tizen.org/api/bluetooth.spp" + +#define BLUETOOTH_DEVICE_CAP_GAP "bluetooth.gap" +#define BLUETOOTH_DEVICE_CAP_SPP "bluetooth.spp" + +namespace TizenApis { +namespace Tizen1_0 { + +const char* bluetoothExportedNames[] = +{ + "adapter", + "setPowered", + "setVisible", + "setName", + "discoverDevices", + "stopDiscovery", + "getKnownDevices", + "getDevice", + "createBonding", + "destroyBonding", + "registerRFCOMMServiceByUUID", + "unregisterRFCOMMService", + "connectToServiceByUUID", + "setSocketNotifier", + "writeData", + "readData", + "close", + "hasService" +}; + +static WrtDeviceApis::Commons::FunctionMapping createBluetoothFunctions(); + +static WrtDeviceApis::Commons::FunctionMapping BluetoothFunctions = + createBluetoothFunctions(); + +DEFINE_FUNCTION_GETTER(Bluetooth, BluetoothFunctions); + +static WrtDeviceApis::Commons::FunctionMapping createBluetoothFunctions() +{ + using namespace WrtDeviceApis::Commons; + + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_BLUETOOTH_GAP, BLUETOOTH_DEVICE_CAP_GAP); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_BLUETOOTH_SPP, BLUETOOTH_DEVICE_CAP_SPP); + + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_BLUETOOTH_GAP); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_BLUETOOTH_GAP, DEVICE_CAP_BLUETOOTH_GAP); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_BLUETOOTH_SPP); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_BLUETOOTH_SPP, DEVICE_CAP_BLUETOOTH_SPP); + + ACE_CREATE_FEATURE(FEATURE_BLUETOOTH, BLUETOOTH_FEATURE_API); + ACE_CREATE_FEATURE(FEATURE_GAP, BLUETOOTH_FEATURE_API_GAP); + ACE_CREATE_FEATURE(FEATURE_SPP, BLUETOOTH_FEATURE_API_SPP); + + ACE_CREATE_FEATURE_LIST(BLUETOOTH_FEATURES_BLUETOOTH_SPP_GAP); + ACE_ADD_API_FEATURE(BLUETOOTH_FEATURES_BLUETOOTH_SPP_GAP, FEATURE_BLUETOOTH); + ACE_ADD_API_FEATURE(BLUETOOTH_FEATURES_BLUETOOTH_SPP_GAP, FEATURE_GAP); + ACE_ADD_API_FEATURE(BLUETOOTH_FEATURES_BLUETOOTH_SPP_GAP, FEATURE_SPP); + + ACE_CREATE_FEATURE_LIST(BLUETOOTH_FEATURES_BLUETOOTH_GAP); + ACE_ADD_API_FEATURE(BLUETOOTH_FEATURES_BLUETOOTH_GAP, FEATURE_BLUETOOTH); + ACE_ADD_API_FEATURE(BLUETOOTH_FEATURES_BLUETOOTH_GAP, FEATURE_GAP); + + ACE_CREATE_FEATURE_LIST(BLUETOOTH_FEATURES_BLUETOOTH_SPP); + ACE_ADD_API_FEATURE(BLUETOOTH_FEATURES_BLUETOOTH_SPP, FEATURE_BLUETOOTH); + ACE_ADD_API_FEATURE(BLUETOOTH_FEATURES_BLUETOOTH_SPP, FEATURE_SPP); + + + FunctionMapping BluetoothFunctions; + + AceFunction adapter = ACE_CREATE_FUNCTION( + FUNCTION_ADAPTER, + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADAPTER], + BLUETOOTH_FEATURES_BLUETOOTH_SPP_GAP, + EMPTY_DEVICE_LIST); + + BluetoothFunctions.insert(std::make_pair( + bluetoothExportedNames[BLUETOOTH_FUNCTION_API_ADAPTER], + adapter)); + + for (int index = BLUETOOTH_FUNCTION_API_ADAPTER_SET_POWERED; + index <= BLUETOOTH_FUNCTION_API_ADPATER_UNREGISTER_RFCOMM; index++) + { + AceFunction gapLoopFunc = ACE_CREATE_FUNCTION( + FUNCTION_GAP_DUMMY_FUNC_ID, + bluetoothExportedNames[index], + BLUETOOTH_FEATURES_BLUETOOTH_GAP, + DEVICE_LIST_BLUETOOTH_GAP); + + BluetoothFunctions.insert(std::make_pair( + bluetoothExportedNames[index], + gapLoopFunc)); + } + + for (int index = BLUETOOTH_FUNCTION_API_DEVICE_CONNECT_TO_SERVICE; + index <= BLUETOOTH_FUNCTION_API_BLUETOOTHCLASS_HAS_SERVICE; index++) + { + AceFunction sppLoopFunc = ACE_CREATE_FUNCTION( + FUNCTION_SPP_DUMMY_FUNC_ID, + bluetoothExportedNames[index], + BLUETOOTH_FEATURES_BLUETOOTH_SPP, + DEVICE_LIST_BLUETOOTH_SPP); + + BluetoothFunctions.insert(std::make_pair( + bluetoothExportedNames[index], + sppLoopFunc)); + } + + return BluetoothFunctions; +} +} +} + +#undef BLUETOOTH_FEATURE_API +#undef BLUETOOTH_FEATURE_API_GAP +#undef BLUETOOTH_FEATURE_API_SPP +#undef BLUETOOTH_DEVICE_CAP_GAP +#undef BLUETOOTH_DEVICE_CAP_SPP diff --git a/src/standards/Tizen/Bluetooth/plugin_config.h b/src/standards/Tizen/Bluetooth/plugin_config.h new file mode 100755 index 0000000..d0a25f6 --- /dev/null +++ b/src/standards/Tizen/Bluetooth/plugin_config.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_TIZEN_JS_BLUETOOTH_PLUGIN_CONFIG_H_ +#define TIZENAPIS_TIZEN_JS_BLUETOOTH_PLUGIN_CONFIG_H_ + +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef enum +{ +BLUETOOTH_FUNCTION_API_ADAPTER = 0, +BLUETOOTH_FUNCTION_API_ADAPTER_SET_POWERED, +BLUETOOTH_FUNCTION_API_ADAPTER_SET_VISIBLE, +BLUETOOTH_FUNCTION_API_ADAPTER_SET_NAME, +BLUETOOTH_FUNCTION_API_ADAPTER_DISCOVER_DEVICES, +BLUETOOTH_FUNCTION_API_ADAPTER_STOP_DISCOVERY, +BLUETOOTH_FUNCTION_API_ADAPTER_GET_KNOWN_DEVICES, +BLUETOOTH_FUNCTION_API_ADAPTER_GET_DEVICE, +BLUETOOTH_FUNCTION_API_ADPATER_CREATE_BONDING, +BLUETOOTH_FUNCTION_API_ADPATER_DESTROY_BONDING, +BLUETOOTH_FUNCTION_API_ADPATER_REGISTER_RFCOMM, +BLUETOOTH_FUNCTION_API_ADPATER_UNREGISTER_RFCOMM, +BLUETOOTH_FUNCTION_API_DEVICE_CONNECT_TO_SERVICE, +BLUETOOTH_FUNCTION_API_SOCKET_SET_SOCKETNOTIFIER, +BLUETOOTH_FUNCTION_API_SOCKET_WRITE_DATA, +BLUETOOTH_FUNCTION_API_SOCKET_READ_DATA, +BLUETOOTH_FUNCTION_API_SOCKET_CLOSE, +BLUETOOTH_FUNCTION_API_BLUETOOTHCLASS_HAS_SERVICE +} bluetoothFuncNames; + + +extern const char* bluetoothExportedNames[]; + +DECLARE_FUNCTION_GETTER(Bluetooth); + +#define BLUETOOTH_CHECK_ACCESS(globalContext, functionName) \ + aceCheckAccess >( \ + globalContext, \ + getBluetoothFunctionData, \ + functionName) +} +} + +#endif diff --git a/src/standards/Tizen/Bluetooth/plugin_initializer.cpp b/src/standards/Tizen/Bluetooth/plugin_initializer.cpp new file mode 100644 index 0000000..a5283ef --- /dev/null +++ b/src/standards/Tizen/Bluetooth/plugin_initializer.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + + +#include "JSBluetoothManager.h" +#include "JSBluetoothAdapter.h" + + +using namespace WrtDeviceApis::Commons; + + +void on_widget_start_callback(int widgetId, JavaScriptContext context, const engine_interface_t *interface) +{ + LogDebug("[Tizen\\Bluetooth ] on_widget_start_callback ("< +#include +#include +#include "JSCalendarItem.h" +#include "JSCalendarItemProperties.h" +#include "JSEventId.h" +#include "CalendarConverter.h" +#include "JSCalendar.h" +#include "JSCalendarManager.h" +#include "JSCategoryArray.h" +#include "JSAttendee.h" +#include "JSRecurrenceRule.h" +#include + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace { +const int DEFAULT_EVENT_INTERVAL = 1; +} + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +std::vector CalendarConverter::m_allowedAttributes; +std::vector CalendarConverter::m_allowedCreateProperties; + +CalendarConverter::CalendarConverter(JSContextRef context, CalendarEvent::CalendarType calendarType) : Converter(context) +{ + LogDebug("entered"); + + m_calendarType = calendarType; + + if (m_allowedAttributes.size() == 0) { // for search filter + m_allowedAttributes.push_back("id"); + m_allowedAttributes.push_back("summary"); + m_allowedAttributes.push_back("description"); + m_allowedAttributes.push_back("location"); + m_allowedAttributes.push_back("category"); + m_allowedAttributes.push_back("status"); + m_allowedAttributes.push_back("initialStartDate"); + m_allowedAttributes.push_back("endStartDate"); + } + if (m_allowedCreateProperties.size() == 0) { + m_allowedCreateProperties.push_back("description"); + m_allowedCreateProperties.push_back("summary"); + m_allowedCreateProperties.push_back("startDate"); + m_allowedCreateProperties.push_back("duration"); + m_allowedCreateProperties.push_back("location"); + m_allowedCreateProperties.push_back("categories"); + m_allowedCreateProperties.push_back("status"); + m_allowedCreateProperties.push_back("alarms"); + m_allowedCreateProperties.push_back("isAllDay"); + m_allowedCreateProperties.push_back("organizer"); + m_allowedCreateProperties.push_back("attendees"); + m_allowedCreateProperties.push_back("position"); + m_allowedCreateProperties.push_back("visibility"); + m_allowedCreateProperties.push_back("lastModifiedDate"); + m_allowedCreateProperties.push_back("availability"); + m_allowedCreateProperties.push_back("recurrenceRule"); + m_allowedCreateProperties.push_back("isDetached"); + m_allowedCreateProperties.push_back("attributesOfInterest"); + } +} + +CalendarConverter::~CalendarConverter() +{ + LogDebug("entered"); +} + +JSValueRef CalendarConverter::toJSValueRefItem(const CalendarEventPtr& arg) +{ + return JSUtils::makeObject(m_context, JSCalendarItem::getClassRef(), arg); +} + +JSValueRef CalendarConverter::toJSValueRef(const CalendarEventListPtr &arg) +{ + return toJSValueRef_(*arg, &CalendarConverter::toJSValueRefItem, this); +} + +JSValueRef CalendarConverter::toJSValueRefItemProperties(const CalendarEventPtr& arg) +{ + return JSUtils::makeObject(m_context, JSCalendarItemProperties::getClassRef(), arg); +} + +JSValueRef CalendarConverter::toJSValueRefCalendar(const ICalendarPtr& arg) +{ + CalendarPrivObject *priv = new CalendarPrivObject(m_context, arg); + return JSObjectMake(m_context, JSCalendar::getClassRef(), priv); +} + +JSValueRef CalendarConverter::toJSValueRef(const std::vector &arg) +{ + return toJSValueRef_(arg, &CalendarConverter::toJSValueRefCalendar, this); +} + +JSValueRef CalendarConverter::toJSValueRef(const EventIdPtr& arg) +{ + return JSUtils::makeObject(m_context, JSEventId::getClassRef(), arg); +} + +CalendarEvent::EventAlarmType CalendarConverter::toEventAlarmType(int tizenValue) +const +{ + switch (tizenValue) { + case JSCalendarManager::NO_ALARM: + return CalendarEvent::NO_ALARM; + case JSCalendarManager::SILENT_ALARM: + return CalendarEvent::SILENT_ALARM; + case JSCalendarManager::SOUND_ALARM: + return CalendarEvent::SOUND_ALARM; + default: + break; + } + ThrowMsg(InvalidArgumentException, "Alarm type has wrong value"); +} + +int CalendarConverter::toTizenValue( + CalendarEvent::EventAlarmType abstractValue) const +{ + switch (abstractValue) { + case CalendarEvent::NO_ALARM: + return JSCalendarManager::NO_ALARM; + case CalendarEvent::SILENT_ALARM: + return JSCalendarManager::SILENT_ALARM; + case CalendarEvent::SOUND_ALARM: + return JSCalendarManager::SOUND_ALARM; + default: + break; + } + ThrowMsg(ConversionException, "Invalid alarm type"); +} + +CalendarEvent::EventStatus CalendarConverter::toEventStatus(std::string tizenValue) const +{ + if(!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_TENTATIVE_STATUS)) + return CalendarEvent::TENTATIVE_STATUS; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_CONFIRMED_STATUS)) + return CalendarEvent::CONFIRMED_STATUS; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_CANCELLED_STATUS)) + return CalendarEvent::CANCELLED_STATUS; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_NEEDS_ACTION_STATUS)) + return CalendarEvent::NEEDS_ACTION_STATUS; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_IN_PROCESS_STATUS)) + return CalendarEvent::IN_PROCESS_STATUS; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_COMPLETED_STATUS)) + return CalendarEvent::COMPLETED_STATUS; + + // default value setting. + if(m_calendarType == CalendarEvent::EVENT_TYPE) { + return CalendarEvent::TENTATIVE_STATUS; + } else { + return CalendarEvent::NEEDS_ACTION_STATUS; + } +} + +std::string CalendarConverter::toTizenValue(CalendarEvent::EventStatus abstractValue) +const +{ + switch (abstractValue) { + case CalendarEvent::TENTATIVE_STATUS: + return TIZEN_CALENDAR_PROPERTY_TENTATIVE_STATUS; + case CalendarEvent::CONFIRMED_STATUS: + return TIZEN_CALENDAR_PROPERTY_CONFIRMED_STATUS; + case CalendarEvent::CANCELLED_STATUS: + return TIZEN_CALENDAR_PROPERTY_CANCELLED_STATUS; + case CalendarEvent::NEEDS_ACTION_STATUS: + return TIZEN_CALENDAR_PROPERTY_NEEDS_ACTION_STATUS; + case CalendarEvent::IN_PROCESS_STATUS: + return TIZEN_CALENDAR_PROPERTY_IN_PROCESS_STATUS; + case CalendarEvent::COMPLETED_STATUS: + return TIZEN_CALENDAR_PROPERTY_COMPLETED_STATUS; + default: + break; + } + + ThrowMsg(ConversionException, "Invalid status"); +} + +EventRecurrenceRule::EventRecurrence CalendarConverter::toRecurrenceFrequency( + std::string tizenValue) const +{ + if(!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_NO_RECURRENCE)) + return EventRecurrenceRule::NO_RECURRENCE; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_DAILY_RECURRENCE)) + return EventRecurrenceRule::DAILY_RECURRENCE; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_WEEKLY_RECURRENCE)) + return EventRecurrenceRule::WEEKLY_RECURRENCE; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_MONTHLY_RECURRENCE)) + return EventRecurrenceRule::MONTHLY_RECURRENCE; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_YEARLY_RECURRENCE)) + return EventRecurrenceRule::YEARLY_RECURRENCE; + + return EventRecurrenceRule::NO_RECURRENCE; +} + +std::string CalendarConverter::toTizenValue( + EventRecurrenceRule::EventRecurrence abstractValue) const +{ + switch (abstractValue) { + case EventRecurrenceRule::NO_RECURRENCE: + return TIZEN_CALENDAR_PROPERTY_NO_RECURRENCE; + case EventRecurrenceRule::DAILY_RECURRENCE: + return TIZEN_CALENDAR_PROPERTY_DAILY_RECURRENCE; + case EventRecurrenceRule::WEEKLY_RECURRENCE: + case EventRecurrenceRule::WEEKDAY_RECURRENCE: + return TIZEN_CALENDAR_PROPERTY_WEEKLY_RECURRENCE; + case EventRecurrenceRule::MONTHLY_RECURRENCE: + case EventRecurrenceRule::MONTHLY_ON_DAY_RECURRENCE: + return TIZEN_CALENDAR_PROPERTY_MONTHLY_RECURRENCE; + case EventRecurrenceRule::YEARLY_RECURRENCE: + return TIZEN_CALENDAR_PROPERTY_YEARLY_RECURRENCE; + default: + break; + } + + return TIZEN_CALENDAR_PROPERTY_NO_RECURRENCE; +} + +EventRecurrenceRulePtr CalendarConverter::toEventRecurrenceRule(JSValueRef rrule) +{ + LogDebug("entered"); + EventRecurrenceRulePtr result(new EventRecurrenceRule()); + const ScopedJSStringRef frequencyStr(JSStringCreateWithUTF8CString(TIZEN_RECURRENCE_RULE_FREQUENCY)); + const ScopedJSStringRef intervalStr(JSStringCreateWithUTF8CString(TIZEN_RECURRENCE_RULE_INTERVAL)); + const ScopedJSStringRef endDateStr(JSStringCreateWithUTF8CString(TIZEN_RECURRENCE_RULE_END_DATE)); + const ScopedJSStringRef occurrenceCountStr(JSStringCreateWithUTF8CString(TIZEN_RECURRENCE_RULE_OCCURRENCE_COUNT)); +// const ScopedJSStringRef daysOfTheMonthStr(JSStringCreateWithUTF8CString(TIZEN_RECURRENCE_RULE_DAYS_OF_THE_MONTH)); + const ScopedJSStringRef daysOfTheWeekStr(JSStringCreateWithUTF8CString(TIZEN_RECURRENCE_RULE_DAYS_OF_THE_WEEK)); +// const ScopedJSStringRef daysOfTheYearStr(JSStringCreateWithUTF8CString(TIZEN_RECURRENCE_RULE_DAYS_OF_THE_YEAR)); +// const ScopedJSStringRef weeksOfTheYearStr(JSStringCreateWithUTF8CString(TIZEN_RECURRENCE_RULE_WEEKS_OF_THE_YEAR)); + const ScopedJSStringRef setPositionStr(JSStringCreateWithUTF8CString(TIZEN_RECURRENCE_RULE_SET_POSITION)); + const ScopedJSStringRef exceptionsStr(JSStringCreateWithUTF8CString(TIZEN_RECURRENCE_RULE_EXCEPTIONS)); + + JSObjectRef arg = toJSObjectRef(rrule); + + JSValueRef frequencyData = JSObjectGetProperty(m_context, arg, frequencyStr.get(), NULL); + JSValueRef intervalData = JSObjectGetProperty(m_context, arg, intervalStr.get(), NULL); + JSValueRef endDateData = JSObjectGetProperty(m_context, arg, endDateStr.get(), NULL); + JSValueRef occurrenceCountData = JSObjectGetProperty(m_context, arg, occurrenceCountStr.get(), NULL); +// JSValueRef daysOfTheMonthData = JSObjectGetProperty(m_context, arg, daysOfTheMonthStr.get(), NULL); + JSValueRef daysOfTheWeekData = JSObjectGetProperty(m_context, arg, daysOfTheWeekStr.get(), NULL); +// JSValueRef daysOfTheYearData = JSObjectGetProperty(m_context, arg, daysOfTheYearStr.get(), NULL); +// JSValueRef weeksOfTheYearData = JSObjectGetProperty(m_context, arg, weeksOfTheYearStr.get(), NULL); + JSValueRef setPositionData = JSObjectGetProperty(m_context, arg, setPositionStr.get(), NULL); + JSValueRef exceptionsData = JSObjectGetProperty(m_context, arg, exceptionsStr.get(), NULL); + + if (!JSValueIsUndefined(m_context, frequencyData)) { + result->setFrequency(toRecurrenceFrequency(toString(frequencyData))); + } + if (!JSValueIsUndefined(m_context, intervalData)) { + result->setInterval(toInt(intervalData)); + } else { + result->setInterval(DEFAULT_EVENT_INTERVAL); + } + if (!JSValueIsUndefined(m_context, endDateData)) { + if (!JSValueIsNull(m_context, endDateData)) { + result->setEndDate(toDateTimeT(endDateData)); + } else { + result->resetEndDate(); + } + } + if (!JSValueIsUndefined(m_context, occurrenceCountData)) { + result->setOccurrenceCount(toLong(occurrenceCountData)); + } +/* if (!JSValueIsUndefined(m_context, daysOfTheMonthData)) { + result->setDaysOfTheMonth(toVectorOfInts(daysOfTheMonthData)); + }*/ + if (!JSValueIsUndefined(m_context, daysOfTheWeekData)) { + result->setDaysOfTheWeek(toVectorOfStrings(daysOfTheWeekData)); + } +/* if (!JSValueIsUndefined(m_context, daysOfTheYearData)) { + result->setDaysOfTheYear(toVectorOfInts(daysOfTheYearData)); + } + if (!JSValueIsUndefined(m_context, weeksOfTheYearData)) { + result->setWeeksOfTheYear(toVectorOfInts(weeksOfTheYearData)); + }*/ + if (!JSValueIsUndefined(m_context, setPositionData)) { + Throw(UnsupportedException); + //result->setSetPosition(toBool(setPositionData)); + } + if (!JSValueIsUndefined(m_context, exceptionsData)) { + result->setExceptions(toVectorOfTimeT(exceptionsData)); + } + + return result; +} + +CalendarEvent::EventVisibility CalendarConverter::toEventVisibility(std::string tizenValue) +const +{ + if(!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_PUBLIC_VISIBILITY)) + return CalendarEvent::PUBLIC_VISIBILITY; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_PRIVATE_VISIBILITY)) + return CalendarEvent::PRIVATE_VISIBILITY; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_CONFIDENTIAL_VISIBILITY)) + return CalendarEvent::CONFIDENTIAL_VISIBILITY; + + return CalendarEvent::PUBLIC_VISIBILITY; +} + +std::string CalendarConverter::toTizenValue( + CalendarEvent::EventVisibility abstractValue) const +{ + switch (abstractValue) { + case CalendarEvent::PUBLIC_VISIBILITY: + return TIZEN_CALENDAR_PROPERTY_PUBLIC_VISIBILITY; + case CalendarEvent::PRIVATE_VISIBILITY: + return TIZEN_CALENDAR_PROPERTY_PRIVATE_VISIBILITY; + case CalendarEvent::CONFIDENTIAL_VISIBILITY: + return TIZEN_CALENDAR_PROPERTY_CONFIDENTIAL_VISIBILITY; + default: + break; + } + + return TIZEN_CALENDAR_PROPERTY_PUBLIC_VISIBILITY; +} + +CalendarEvent::EventAvailability CalendarConverter::toEventAvailability(std::string tizenValue) +const +{ + if(!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_BUSY)) + return CalendarEvent::BUSY_FB; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_BUSY_UNAVAILABLE_FB)) + return CalendarEvent::BUSY_UNAVAILABLE_FB; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_FREE)) + return CalendarEvent::FREE_FB; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_BUSY_TENTATIVE)) + return CalendarEvent::BUSY_TENTATIVE_FB; + + return CalendarEvent::BUSY_FB; +} + +std::string CalendarConverter::toTizenValue( + CalendarEvent::EventAvailability abstractValue) const +{ + switch (abstractValue) { + case CalendarEvent::BUSY_FB: + return TIZEN_CALENDAR_PROPERTY_BUSY; + case CalendarEvent::BUSY_UNAVAILABLE_FB: + return TIZEN_CALENDAR_PROPERTY_BUSY_UNAVAILABLE_FB; + case CalendarEvent::FREE_FB: + return TIZEN_CALENDAR_PROPERTY_FREE; + case CalendarEvent::BUSY_TENTATIVE_FB: + return TIZEN_CALENDAR_PROPERTY_BUSY_TENTATIVE; + default: + break; + } + + return TIZEN_CALENDAR_PROPERTY_BUSY; +} + +EventAttendee::EventAttendeeRole CalendarConverter::toEventAttendeeRole(std::string tizenValue) +const +{ + if(!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_REQ_PARTICIPANT_ROLE)) + return EventAttendee::REQ_PARTICIPANT_ROLE; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_OPT_PARTICIPANT_ROLE)) + return EventAttendee::OPT_PARTICIPANT_ROLE; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_NON_PARTICIPANT_ROLE)) + return EventAttendee::NON_PARTICIPANT_ROLE; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_CHAIR_ROLE)) + return EventAttendee::CHAIR_ROLE; + + return EventAttendee::REQ_PARTICIPANT_ROLE; +} + +std::string CalendarConverter::toTizenValue( + EventAttendee::EventAttendeeRole abstractValue) const +{ + switch (abstractValue) { + case EventAttendee::REQ_PARTICIPANT_ROLE: + return TIZEN_CALENDAR_PROPERTY_REQ_PARTICIPANT_ROLE; + case EventAttendee::OPT_PARTICIPANT_ROLE: + return TIZEN_CALENDAR_PROPERTY_OPT_PARTICIPANT_ROLE; + case EventAttendee::NON_PARTICIPANT_ROLE: + return TIZEN_CALENDAR_PROPERTY_NON_PARTICIPANT_ROLE; + case EventAttendee::CHAIR_ROLE: + return TIZEN_CALENDAR_PROPERTY_CHAIR_ROLE; + default: + break; + } + return TIZEN_CALENDAR_PROPERTY_REQ_PARTICIPANT_ROLE; +} + +EventAttendee::EventAttendeeStatus CalendarConverter::toEventAttendeeStatus(std::string tizenValue) +const +{ + if(!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_PENDING_STATUS)) + return EventAttendee::PENDING_AT_STATUS; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_ACCEPTED_STATUS)) + return EventAttendee::ACCEPTED_AT_STATUS; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_DECLINED_STATUS)) + return EventAttendee::DECLINED_AT_STATUS; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_TENTATIVE_STATUS)) + return EventAttendee::TENTATIVE_AT_STATUS; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_DELEGATED_STATUS)) + return EventAttendee::DELEGATED_AT_STATUS; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_COMPLETED_STATUS)) + return EventAttendee::COMPLETED_AT_STATUS; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_IN_PROCESS_STATUS)) + return EventAttendee::IN_PROCESS_AT_STATUS; + + return EventAttendee::PENDING_AT_STATUS; +} + +std::string CalendarConverter::toTizenValue( + EventAttendee::EventAttendeeStatus abstractValue) const +{ + switch (abstractValue) { + case EventAttendee::PENDING_AT_STATUS: + return TIZEN_CALENDAR_PROPERTY_PENDING_STATUS; + case EventAttendee::ACCEPTED_AT_STATUS: + return TIZEN_CALENDAR_PROPERTY_ACCEPTED_STATUS; + case EventAttendee::DECLINED_AT_STATUS: + return TIZEN_CALENDAR_PROPERTY_DECLINED_STATUS; + case EventAttendee::TENTATIVE_AT_STATUS: + return TIZEN_CALENDAR_PROPERTY_TENTATIVE_STATUS; + case EventAttendee::DELEGATED_AT_STATUS: + return TIZEN_CALENDAR_PROPERTY_DELEGATED_STATUS; + case EventAttendee::COMPLETED_AT_STATUS: + return TIZEN_CALENDAR_PROPERTY_COMPLETED_STATUS; + case EventAttendee::IN_PROCESS_AT_STATUS: + return TIZEN_CALENDAR_PROPERTY_IN_PROCESS_STATUS; + default: + break; + } + return TIZEN_CALENDAR_PROPERTY_PENDING_STATUS; +} + +EventAttendee::EventAttendeeType CalendarConverter::toEventAttendeeType(std::string tizenValue) +const +{ + if(!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_INDIVIDUAL_TYPE)) + return EventAttendee::INDIVIDUAL_TYPE; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_GROUP_TYPE)) + return EventAttendee::GROUP_TYPE; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_RESOURCE_TYPE)) + return EventAttendee::RESOURCE_TYPE; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_ROOM_TYPE)) + return EventAttendee::ROOM_TYPE; + else if (!tizenValue.compare(TIZEN_CALENDAR_PROPERTY_UNKNOWN_TYPE)) + return EventAttendee::UNKNOWN_TYPE; + + return EventAttendee::INDIVIDUAL_TYPE; +} + +std::string CalendarConverter::toTizenValue( + EventAttendee::EventAttendeeType abstractValue) const +{ + switch (abstractValue) { + case EventAttendee::INDIVIDUAL_TYPE: + return TIZEN_CALENDAR_PROPERTY_INDIVIDUAL_TYPE; + case EventAttendee::GROUP_TYPE: + return TIZEN_CALENDAR_PROPERTY_GROUP_TYPE; + case EventAttendee::RESOURCE_TYPE: + return TIZEN_CALENDAR_PROPERTY_RESOURCE_TYPE; + case EventAttendee::ROOM_TYPE: + return TIZEN_CALENDAR_PROPERTY_ROOM_TYPE; + case EventAttendee::UNKNOWN_TYPE: + return TIZEN_CALENDAR_PROPERTY_UNKNOWN_TYPE; + default: + break; + } + + return TIZEN_CALENDAR_PROPERTY_INDIVIDUAL_TYPE; +} + +JSValueRef CalendarConverter::toFunctionOrNull(const JSValueRef& arg) +{ + if (Validator(m_context).isCallback(arg)) { + return arg; + } else if (!JSValueIsNull(m_context, + arg) && !JSValueIsUndefined(m_context, arg)) { + ThrowMsg(InvalidArgumentException, "Not a function nor JS null."); + } + return NULL; +} + +JSValueRef CalendarConverter::toFunction(const JSValueRef& arg) +{ + if (Validator(m_context).isCallback(arg)) { + return arg; + } else if (JSValueIsNull(m_context, + arg) || JSValueIsUndefined(m_context, arg)) { + ThrowMsg(ConversionException, "JS null passed as function."); + } + ThrowMsg(InvalidArgumentException, "Not a function nor JS null."); +} + +void CalendarConverter::toEventFilterConvertId( + const EventFilterPtr &result, + const JSValueRef &filters) +{ + const ScopedJSStringRef idStr(JSStringCreateWithUTF8CString("id")); + JSObjectRef filterObj = toJSObjectRef(filters); + if (JSObjectHasProperty(m_context, filterObj, idStr.get())) { + LogDebug("converting id"); + JSValueRef value = JSObjectGetProperty(m_context, filterObj, + idStr.get(), NULL); + result->setIdFilter(toString(value)); + } +} + +void CalendarConverter::toEventFilterConvertSummary( + const EventFilterPtr &result, + const JSValueRef &filters) +{ + const ScopedJSStringRef summaryStr(JSStringCreateWithUTF8CString("summary")); + JSObjectRef filterObj = toJSObjectRef(filters); + if (JSObjectHasProperty(m_context, filterObj, summaryStr.get())) { + LogDebug("converting summary"); + JSValueRef value = JSObjectGetProperty(m_context, + filterObj, + summaryStr.get(), + NULL); + result->setSubjectFilter(toString(value)); + } +} + +void CalendarConverter::toEventFilterConvertDescription( + const EventFilterPtr &result, + const JSValueRef &filters) +{ + const ScopedJSStringRef descriptionStr(JSStringCreateWithUTF8CString( + "description")); + JSObjectRef filterObj = toJSObjectRef(filters); + if (JSObjectHasProperty(m_context, filterObj, descriptionStr.get())) { + LogDebug("converting description"); + JSValueRef value = JSObjectGetProperty(m_context, + filterObj, + descriptionStr.get(), + NULL); + result->setDescriptionFilter(toString(value)); + } +} + +void CalendarConverter::toEventFilterConvertLocation( + const EventFilterPtr &result, + const JSValueRef &filters) +{ + const ScopedJSStringRef locationStr(JSStringCreateWithUTF8CString( + "location")); + JSObjectRef filterObj = toJSObjectRef(filters); + if (JSObjectHasProperty(m_context, filterObj, locationStr.get())) { + LogDebug("converting location"); + JSValueRef value = JSObjectGetProperty(m_context, + filterObj, + locationStr.get(), + NULL); + result->setLocationFilter(toString(value)); + } +} + +void CalendarConverter::toEventFilterConvertCategory( + const EventFilterPtr &result, + const JSValueRef &filters) +{ + const ScopedJSStringRef locationStr(JSStringCreateWithUTF8CString( + "category")); + JSObjectRef filterObj = toJSObjectRef(filters); + if (JSObjectHasProperty(m_context, filterObj, locationStr.get())) { + LogDebug("converting category"); + JSValueRef value = JSObjectGetProperty(m_context, + filterObj, + locationStr.get(), + NULL); + result->setCategoryFilter(toString(value)); + } +} + +void CalendarConverter::toEventFilterConvertStatus( + const EventFilterPtr &result, + const JSValueRef &filters) +{ + const ScopedJSStringRef statusStr(JSStringCreateWithUTF8CString("status")); + JSObjectRef filterObj = toJSObjectRef(filters); + if (JSObjectHasProperty(m_context, filterObj, statusStr.get())) { + LogDebug("converting status"); + JSValueRef value = JSObjectGetProperty(m_context, + filterObj, + statusStr.get(), + NULL); + std::vector statuses = toVectorOfStrings(value); + for (std::size_t i = 0; i < statuses.size(); ++i) { + CalendarEvent::EventStatus status(toEventStatus(statuses[i])); + if (status == CalendarEvent::INVALID_STATUS) { + ThrowMsg(InvalidArgumentException, + "Status filter has wrong value"); + } + result->addStatusFilter(status); + } + } +} + +void CalendarConverter::toEventFilterConvertStartTime( + const EventFilterPtr &result, + const JSValueRef &filters) +{ + const ScopedJSStringRef initialStartDateStr(JSStringCreateWithUTF8CString( + "initialStartDate")); + const ScopedJSStringRef endStartDateStr(JSStringCreateWithUTF8CString( + "endStartDate")); + JSObjectRef filterObj = toJSObjectRef(filters); + if (JSObjectHasProperty(m_context, filterObj, initialStartDateStr.get()) || + JSObjectHasProperty(m_context, filterObj, endStartDateStr.get())) { + LogDebug("converting startTime"); + JSValueRef valueStart = JSObjectGetProperty(m_context, + filterObj, + initialStartDateStr.get(), + NULL); + JSValueRef valueEnd = JSObjectGetProperty(m_context, + filterObj, + endStartDateStr.get(), + NULL); + //no filters + if ((JSValueIsNull(m_context, + valueStart) || + JSValueIsUndefined(m_context, valueStart)) && + (JSValueIsNull(m_context, + valueEnd) || + JSValueIsUndefined(m_context, valueEnd))) { + return; + } + //start + if (!JSValueIsNull(m_context, valueStart) && + !JSValueIsUndefined(m_context, valueStart)) { + result->setStartTimeMinFilter(toDateTimeT(valueStart)); + } + //end + if (!JSValueIsNull(m_context, valueEnd) && + !JSValueIsUndefined(m_context, valueEnd)) { + result->setStartTimeMaxFilter(toDateTimeT(valueEnd)); + } + } +} + +EventFilterPtr CalendarConverter::toEventFilter(const JSValueRef &filters) +{ + LogDebug("entered"); + EventFilterPtr result(new EventFilter()); + Validator validator(m_context); + if (!JSValueIsObject(m_context, filters)) { + LogError("Wrong filter parameter"); + Throw(InvalidArgumentException); + } + if (!validator.checkArrayKeys(m_allowedAttributes, filters)) { + LogError("Wrong filter's attribue"); + Throw(ConversionException); + } + toEventFilterConvertId(result, filters); + toEventFilterConvertSummary(result, filters); + toEventFilterConvertDescription(result, filters); + toEventFilterConvertLocation(result, filters); + toEventFilterConvertCategory(result, filters); + toEventFilterConvertStatus(result, filters); + toEventFilterConvertStartTime(result, filters); + return result; +} + +CategoryListPtr CalendarConverter::toCategories(JSValueRef categories) +{ + LogDebug("entered"); + if (JSValueIsObjectOfClass(m_context, categories, + JSCategoryArray::getClassRef())) { + return JSCategoryArray::getCategories(m_context, + toJSObjectRef(categories)); + } + CategoryListPtr result(new CategoryList()); + *result = toVectorOfStrings(categories); + return result; +} + +EventAttendeePtr CalendarConverter::toAttendee(JSValueRef attendee) +{ + LogDebug("entered"); + EventAttendeePtr result(new EventAttendee()); + const ScopedJSStringRef nameStr(JSStringCreateWithUTF8CString("name")); + const ScopedJSStringRef uriStr(JSStringCreateWithUTF8CString("uri")); + const ScopedJSStringRef roleStr(JSStringCreateWithUTF8CString("role")); + const ScopedJSStringRef statusStr(JSStringCreateWithUTF8CString("status")); + const ScopedJSStringRef RSVPStr(JSStringCreateWithUTF8CString("RSVP")); + const ScopedJSStringRef typeStr(JSStringCreateWithUTF8CString("type")); + const ScopedJSStringRef groupStr(JSStringCreateWithUTF8CString("group")); + const ScopedJSStringRef delegatorURIStr(JSStringCreateWithUTF8CString("delegatorURI")); + const ScopedJSStringRef delegateURIStr(JSStringCreateWithUTF8CString("delegateURI")); + const ScopedJSStringRef uidStr(JSStringCreateWithUTF8CString("uid")); + + JSObjectRef arg = toJSObjectRef(attendee); + + JSValueRef nameData = JSObjectGetProperty(m_context, arg, nameStr.get(), NULL); + JSValueRef uriData = JSObjectGetProperty(m_context, arg, uriStr.get(), NULL); + JSValueRef roleData = JSObjectGetProperty(m_context, arg, roleStr.get(), NULL); + JSValueRef statusData = JSObjectGetProperty(m_context, arg, statusStr.get(), NULL); + JSValueRef RSVPData = JSObjectGetProperty(m_context, arg, RSVPStr.get(), NULL); + JSValueRef typeData = JSObjectGetProperty(m_context, arg, typeStr.get(), NULL); + JSValueRef groupData = JSObjectGetProperty(m_context, arg, groupStr.get(), NULL); + JSValueRef delegatorURIData = JSObjectGetProperty(m_context, arg, delegatorURIStr.get(), NULL); + JSValueRef delegateURIData = JSObjectGetProperty(m_context, arg, delegateURIStr.get(), NULL); + JSValueRef uidData = JSObjectGetProperty(m_context, arg, uidStr.get(), NULL); + + if (!JSValueIsUndefined(m_context, nameData)) { + result->setName(toString(nameData)); + } + if (!JSValueIsUndefined(m_context, uriData)) { + result->setURI(toString(uriData)); + } + if (!JSValueIsUndefined(m_context, roleData)) { + result->setRole(toEventAttendeeRole(toString(roleData))); + } + if (!JSValueIsUndefined(m_context, statusData)) { + result->setStatus(toEventAttendeeStatus(toString(statusData))); + } + if (!JSValueIsUndefined(m_context, RSVPData)) { + result->setRSVP(toBool(RSVPData)); + } + if (!JSValueIsUndefined(m_context, typeData)) { + result->setType(toEventAttendeeType(toString(typeData))); + } + if (!JSValueIsUndefined(m_context, groupData)) { + result->setGroup(toString(groupData)); + } + if (!JSValueIsUndefined(m_context, delegatorURIData)) { + result->setDelegatorURI(toString(delegatorURIData)); + } + if (!JSValueIsUndefined(m_context, delegateURIData)) { + result->setDelegateURI(toString(delegateURIData)); + } + if (!JSValueIsUndefined(m_context, uidData)) { + result->setPersonId(toString(uidData)); + } + + return result; +} + +EventAttendeeListPtr CalendarConverter::toVectorOfAttendees(JSValueRef attendees) +{ + LogDebug("entered"); + EventAttendeeListPtr result(new EventAttendeeList()); + + std::vector resultVector; + JSObjectRef objArg = toJSObjectRef(attendees); + LogDebug("array length "<setAbsoluteDate(toDateTimeT(absoluteDateData)); + } + if (!JSValueIsUndefined(m_context, minutesData)) { + result->setMinutes(toLong(minutesData)); + } + if (!JSValueIsUndefined(m_context, daysData)) { + result->setDays(toLong(daysData)); + } + if (!JSValueIsUndefined(m_context, methodsData)) { + result->setMethods(toVectorOfInts(methodsData)); + } + + return result; +} + +EventAlarmListPtr CalendarConverter::toVectorOfEventAlarms(JSValueRef alarms) +{ + LogDebug("entered"); + EventAlarmListPtr result(new EventAlarmList()); + + std::vector resultVector; + JSObjectRef objArg = toJSObjectRef(alarms); + LogDebug("array length "<setDescription(toString(descriptionData)); + } + if (!JSValueIsUndefined(m_context, summaryData)) { + result->setSubject(toString(summaryData)); + } + //It's important to set startTime before duration to set end date by time_t + if (!JSValueIsUndefined(m_context, startTimeData)) { + result->setStartTime(timeUtilConverter.toTZDateTimeT(startTimeData)); + result->setTimeZone(timeUtilConverter.getPropertiesInTZDate(startTimeData).timezone); + } else { + //set default value, current local time. + if(m_calendarType == CalendarEvent::EVENT_TYPE) { + result->setStartTime(std::time(NULL)); + } + } + if (!JSValueIsUndefined(m_context, durationData)) { + long length = timeUtilConverter.getDurationLength(durationData, NULL); + int unit = timeUtilConverter.getDurationUnit(durationData, NULL); + LogInfo("duration length: "<setEndTime(result->getStartTime() + length); + } else if ( MINUTES_UNIT==unit ) { + result->setEndTime(result->getStartTime() + length*60); + } else if ( HOURS_UNIT==unit ) { + result->setEndTime(result->getStartTime() + length*60*60); + } else if ( DAYS_UNIT==unit ) { + result->setEndTime(result->getStartTime() + length*24*60*60); + } else { + Throw(ConversionException); + } + } else { + //default duration is 3600 seconds, or 1 hour. + LogInfo("duration length is 3600"); + result->setEndTime(result->getStartTime() + 3600); + } + if (!JSValueIsUndefined(m_context, locationData)) { + result->setLocation(toString(locationData)); + } + if (!JSValueIsUndefined(m_context, categoriesData)) { + CategoryListPtr categories(new CategoryList()); + *categories = toVectorOfStrings(categoriesData); + result->setCategories(categories); + } + if (!JSValueIsUndefined(m_context, statusData)) { + result->setStatus(toEventStatus(toString(statusData))); + } else { + result->setStatus(CalendarEvent::CONFIRMED_STATUS); + } + if (!JSValueIsUndefined(m_context, alarmsData)) { + EventAlarmListPtr alarms = toVectorOfEventAlarms(alarmsData); + std::vector alarmsType; + std::vector alarmsTick; + // Set the multiple alarms. + for( unsigned int i=0; isize(); i++) { + EventAlarmPtr theAlarm = alarms->at(i); + alarmsType.push_back(toEventAlarmType(theAlarm->getMethods().at(0))); + if( 0 < theAlarm->getAbsoluteDate() ) { + alarmsTick.push_back(theAlarm->getAbsoluteDate()/60); // minutes only in platform. + } else { + alarmsTick.push_back(theAlarm->getMinutes() + theAlarm->getDays()*24*60); + } + } + result->setAlarmsType(alarmsType); + result->setAlarmsTick(alarmsTick); + } + if (!JSValueIsUndefined(m_context, isAllDayData)) { + result->setIsAllDay(toBool(isAllDayData)); + } + if (!JSValueIsUndefined(m_context, organizerData)) { + result->setOrganizer(toString(organizerData)); + } + if (!JSValueIsUndefined(m_context, attendeesData)) { + EventAttendeeListPtr attendees = toVectorOfAttendees(attendeesData); + result->setAttendees(attendees); + } + if (!JSValueIsUndefined(m_context, latitudeData)) { + result->setLatitude(toDouble(latitudeData)); + } + if (!JSValueIsUndefined(m_context, longitudeData)) { + result->setLongitude(toDouble(longitudeData)); + } + if (!JSValueIsUndefined(m_context, visibilityData)) { + result->setVisibility(toEventVisibility(toString(visibilityData))); + } + /* This feature is read only. + if (!JSValueIsUndefined(m_context, lastModifiedDateData)) { + result->setLastModifiedDate(toDateTimeT(lastModifiedDateData)); + } */ + if (!JSValueIsUndefined(m_context, availabilityData)) { + result->setAvailability(toEventAvailability(toString(availabilityData))); + } + if (!JSValueIsUndefined(m_context, recurrenceRuleData)) { + result->setRecurrenceRule(toEventRecurrenceRule(recurrenceRuleData)); + } + /* attributesOfInterest is not supported + if (!JSValueIsUndefined(m_context, attributesOfInterestData)) { + AttributeList alist = toVectorOfStrings(attributesOfInterestData); + AttributeListPtr attributesOfInterest = AttributeListPtr(new AttributeList()); + *attributesOfInterest = alist; + result->setAttributesOfInterest(attributesOfInterest); + }*/ + if (!JSValueIsUndefined(m_context, priorityData)) { + result->setPriority(toTaskPriority(toString(priorityData))); + } + if (!JSValueIsUndefined(m_context, dueDateData)) { + result->setEndTime(timeUtilConverter.toTZDateTimeT(dueDateData)); + } + if (!JSValueIsUndefined(m_context, completedDateData)) { + result->setCompletedDate(timeUtilConverter.toTZDateTimeT(completedDateData)); + } + if (!JSValueIsUndefined(m_context, progressData)) { + result->setProgress(toInt(progressData)); + } + + return result; +} + +CalendarEventListPtr CalendarConverter::toVectorOfEvents(JSValueRef events) +{ + LogDebug("entered"); + CalendarEventListPtr result(new CalendarEventList()); + + std::vector resultVector; + JSObjectRef objArg = toJSObjectRef(events); + LogDebug("array length "< resultVector; + JSObjectRef objArg = toJSObjectRef(events); + LogDebug("array length "<setUId(toString(uidData)); + } + if (!JSValueIsUndefined(m_context, recurrenceIdData)) { + TimeUtilConverter timeUtilConverter(m_context); + result->setRecurrenceId(timeUtilConverter.toTZDateTimeT(recurrenceIdData)); + } + + return result; +} + +EventIdListPtr CalendarConverter::toVectorOfEventIds(JSValueRef eventIds) +{ + LogDebug("entered"); + EventIdListPtr result(new EventIdList()); + + std::vector resultVector; + JSObjectRef objArg = toJSObjectRef(eventIds); + LogDebug("array length "< CalendarConverter::toVectorOfTimeTFromTZDate(JSValueRef dates) +{ + LogDebug("entered"); + std::vector result; + TimeUtilConverter converter(m_context); + + JSObjectRef objArg = toJSObjectRef(dates); + LogDebug("array length "< +#include +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +class CalendarConverter : public WrtDeviceApis::CommonsJavaScript::Converter +{ + public: + using Converter::toJSValueRef; + public: + explicit CalendarConverter(JSContextRef context, TizenApis::Api::Calendar::CalendarEvent::CalendarType calendarType=TizenApis::Api::Calendar::CalendarEvent::EVENT_TYPE); + virtual ~CalendarConverter(); + TizenApis::Api::Calendar::EventFilterPtr toEventFilter(const JSValueRef &filters); + TizenApis::Api::Calendar::CalendarEventPtr toEvent(const JSValueRef event); + TizenApis::Api::Calendar::CalendarEventListPtr toVectorOfEvents(JSValueRef events); + TizenApis::Api::Calendar::CalendarEventListPtr toVectorOfEventsFromProperty(JSValueRef events); + TizenApis::Api::Calendar::CategoryListPtr toCategories(JSValueRef categories); + TizenApis::Api::Calendar::EventAttendeePtr toAttendee(JSValueRef attendee); + TizenApis::Api::Calendar::EventAttendeeListPtr toVectorOfAttendees(JSValueRef attendees); + + TizenApis::Api::Calendar::CalendarEvent::EventAlarmType toEventAlarmType(int tizenValue) const; + TizenApis::Api::Calendar::CalendarEvent::EventStatus toEventStatus(std::string tizenValue) const; + TizenApis::Api::Calendar::EventRecurrenceRule::EventRecurrence toRecurrenceFrequency(std::string tizenValue) const; + TizenApis::Api::Calendar::EventRecurrenceRulePtr toEventRecurrenceRule(JSValueRef rrule); + + TizenApis::Api::Calendar::CalendarEvent::EventVisibility toEventVisibility(std::string tizenValue) const; + TizenApis::Api::Calendar::CalendarEvent::EventAvailability toEventAvailability(std::string tizenValue) const; + TizenApis::Api::Calendar::EventAttendee::EventAttendeeRole toEventAttendeeRole(std::string tizenValue) const; + TizenApis::Api::Calendar::EventAttendee::EventAttendeeStatus toEventAttendeeStatus(std::string tizenValue) const; + TizenApis::Api::Calendar::EventAttendee::EventAttendeeType toEventAttendeeType(std::string tizenValue) const; + + int toTizenValue(TizenApis::Api::Calendar::CalendarEvent::EventAlarmType abstractValue) const; + std::string toTizenValue(TizenApis::Api::Calendar::CalendarEvent::EventStatus abstractValue) const; + std::string toTizenValue(TizenApis::Api::Calendar::EventRecurrenceRule::EventRecurrence abstractValue) const; + std::string toTizenValue(TizenApis::Api::Calendar::CalendarEvent::EventVisibility abstractValue) const; + std::string toTizenValue(TizenApis::Api::Calendar::CalendarEvent::EventAvailability abstractValue) const; + std::string toTizenValue(TizenApis::Api::Calendar::EventAttendee::EventAttendeeRole abstractValue) const; + std::string toTizenValue(TizenApis::Api::Calendar::EventAttendee::EventAttendeeStatus abstractValue) const; + std::string toTizenValue(TizenApis::Api::Calendar::EventAttendee::EventAttendeeType abstractValue) const; + std::string toTizenValue(TizenApis::Api::Calendar::CalendarEvent::TaskPriority abstractValue) const; + + JSValueRef toJSValueRefItem(const TizenApis::Api::Calendar::CalendarEventPtr& arg); + JSValueRef toJSValueRef(const TizenApis::Api::Calendar::CalendarEventListPtr &arg); + JSValueRef toJSValueRefCalendar(const TizenApis::Api::Calendar::ICalendarPtr& arg); + JSValueRef toJSValueRef(const std::vector &arg); + JSValueRef toJSValueRefItemProperties(const TizenApis::Api::Calendar::CalendarEventPtr& arg); + JSValueRef toJSValueRef(const TizenApis::Api::Calendar::EventIdPtr& arg); + + TizenApis::Api::Calendar::EventAlarmPtr toEventAlarm(JSValueRef alarm); + TizenApis::Api::Calendar::EventAlarmListPtr toVectorOfEventAlarms(JSValueRef alarms); + TizenApis::Api::Calendar::EventIdPtr toEventId(JSValueRef eventId); + TizenApis::Api::Calendar::EventIdListPtr toVectorOfEventIds(JSValueRef eventIds); + std::vector toVectorOfTimeTFromTZDate(JSValueRef dates); + TizenApis::Api::Calendar::CalendarEvent::TaskPriority toTaskPriority(std::string priority) const; + TizenApis::Api::Calendar::CalendarEvent::CalendarType toCalendarType(std::string type) const; + TizenApis::Api::Calendar::CalendarEvent::VObjectFormat toVObjectFormat(std::string type) const; + + /** + * @throw InvalidArgumentException If not a callback nor JS null. + */ + JSValueRef toFunctionOrNull(const JSValueRef& arg); + + /** + * @throw ConversionException If JS null. + * @throw InvalidArgumentException If not a callback nor JS null. + */ + JSValueRef toFunction(const JSValueRef& arg); + + private: + void toEventFilterConvertId(const TizenApis::Api::Calendar::EventFilterPtr &result, + const JSValueRef &filters); + void toEventFilterConvertSummary(const TizenApis::Api::Calendar::EventFilterPtr &result, + const JSValueRef &filters); + void toEventFilterConvertDescription(const TizenApis::Api::Calendar::EventFilterPtr &result, + const JSValueRef &filters); + void toEventFilterConvertLocation(const TizenApis::Api::Calendar::EventFilterPtr &result, + const JSValueRef &filters); + void toEventFilterConvertCategory(const TizenApis::Api::Calendar::EventFilterPtr &result, + const JSValueRef &filters); + void toEventFilterConvertStatus(const TizenApis::Api::Calendar::EventFilterPtr &result, + const JSValueRef &filters); + void toEventFilterConvertStartTime(const TizenApis::Api::Calendar::EventFilterPtr &result, + const JSValueRef &filters); + + static std::vector m_allowedAttributes; + static std::vector m_allowedCreateProperties; + TizenApis::Api::Calendar::CalendarEvent::CalendarType m_calendarType; +}; + +typedef WrtDeviceApis::CommonsJavaScript::ConverterFactory CalendarConverterFactory; + +} +} +} + +#endif /* _JS_TIZEN_CALENDAR_CONVERTER_H_ */ diff --git a/src/standards/Tizen/Calendar/CalendarMultiCallback.h b/src/standards/Tizen/Calendar/CalendarMultiCallback.h new file mode 100755 index 0000000..1868de5 --- /dev/null +++ b/src/standards/Tizen/Calendar/CalendarMultiCallback.h @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _CALENDAR_MULTI_CALLBACK_H_ +#define _CALENDAR_MULTI_CALLBACK_H_ + +#include +#include +#include +#include +#include "API/Calendar/CalendarEvent.h" + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +struct CalendarEventsSuccessCallback { + JSValueRef onSuccess; + JSValueRef onEventSuccess; + JSValueRef onEventError; + + CalendarEventsSuccessCallback() + : onSuccess(NULL), + onEventSuccess(NULL), + onEventError(NULL) + { } +}; + +class CalendarEventsCallbackPrivateData : public WrtDeviceApis::Commons::IEventPrivateData +{ +public: + CalendarEventsCallbackPrivateData(const JSCallbackManagerPtr& onSuccess, + const JSCallbackManagerPtr& onEvent): m_onSuccess(onSuccess), + m_onEvent(onEvent) + { + } + + JSCallbackManagerPtr getOnSuccess() const + { + return m_onSuccess; + } + JSCallbackManagerPtr getOnEvent() const + { + return m_onEvent; + } + +private: + JSCallbackManagerPtr m_onSuccess; + JSCallbackManagerPtr m_onEvent; +}; +typedef DPL::SharedPtr CalendarEventsCallbackPrivateDataPtr; + +struct CalendarChangeCallback { + JSValueRef onAdded; + JSValueRef onUpdated; + JSValueRef onDeleted; + //JSValueRef onCalendarReset; + + CalendarChangeCallback() + : onAdded(NULL), + onUpdated(NULL), + onDeleted(NULL) + //onCalendarReset(NULL) + { } +}; + +class CalendarChangeCallbackPrivateData : public WrtDeviceApis::Commons::IEventPrivateData +{ +public: + CalendarChangeCallbackPrivateData(const JSCallbackManagerPtr& onAdded, + const JSCallbackManagerPtr& onUpdated, const JSCallbackManagerPtr& onDeleted): + //const JSCallbackManagerPtr& onCalendarReset): + m_onAdded(onAdded), + m_onUpdated(onUpdated), + m_onDeleted(onDeleted) + //m_onCalendarReset(onCalendarReset) + { + } + + JSCallbackManagerPtr getOnAdded() const + { + return m_onAdded; + } + JSCallbackManagerPtr getOnUpdated() const + { + return m_onUpdated; + } + JSCallbackManagerPtr getOnDeleted() const + { + return m_onDeleted; + } + + /* + JSCallbackManagerPtr getOnCalendarReset() const + { + return m_onCalendarReset; + } + */ + + private: + JSCallbackManagerPtr m_onAdded; + JSCallbackManagerPtr m_onUpdated; + JSCallbackManagerPtr m_onDeleted; + //JSCallbackManagerPtr m_onCalendarReset; +}; +typedef DPL::SharedPtr CalendarChangeCallbackPrivateDataPtr; + +} +} +} + +#endif /* _CALENDAR_MULTI_CALLBACK_H_ */ diff --git a/src/standards/Tizen/Calendar/CalendarResponseDispatcher.cpp b/src/standards/Tizen/Calendar/CalendarResponseDispatcher.cpp new file mode 100755 index 0000000..ae3da9d --- /dev/null +++ b/src/standards/Tizen/Calendar/CalendarResponseDispatcher.cpp @@ -0,0 +1,432 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "CalendarResponseDispatcher.h" +#include +#include +#include +#include +#include "CalendarConverter.h" +#include "JSCalendarItem.h" +#include "JSEventId.h" +#include "CalendarMultiCallback.h" +#include + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +CalendarResponseDispatcher& CalendarResponseDispatcher::getInstance() +{ + static CalendarResponseDispatcher instance; + return instance; +} + +CalendarResponseDispatcher::CalendarResponseDispatcher() : + GetCalendarsEventAnswerReceiver(ThreadEnum::NULL_THREAD), + CalendarEventsEventAnswerReceiverAdds(ThreadEnum::NULL_THREAD), + CalendarEventsEventAnswerReceiverDeletes(ThreadEnum::NULL_THREAD), + CalendarEventsEventAnswerReceiverUpdates(ThreadEnum::NULL_THREAD), + CalendarEventsEventAnswerReceiverFind(ThreadEnum::NULL_THREAD), + CalendarEventsEventAnswerReceiverExpand(ThreadEnum::NULL_THREAD), + OnAddEventsChangedListener(ThreadEnum::NULL_THREAD), + OnUpdateEventsChangedListener(ThreadEnum::NULL_THREAD), + OnDeleteEventsChangedListener(ThreadEnum::NULL_THREAD), + OnEventsChangedListener(ThreadEnum::NULL_THREAD) +{ + LogDebug("entered"); +} + +CalendarResponseDispatcher::~CalendarResponseDispatcher() +{ + LogDebug("entered"); +} + +void CalendarResponseDispatcher::OnAnswerReceived( + const IEventGetCalendarsPtr &event) +{ + LogDebug("entered"); + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + if (!cbm) { + LogError("no callback manager"); + return; + } + Try + { + if (event->getResult()) { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(cbm->getContext()); + const std::vector &results = event->getCalendars(); + LogDebug("found calendars: " << results.size()); + JSValueRef result = converter->toJSValueRef(results); + cbm->callOnSuccess(result); + return; + } + } + Catch(Exception) + { + LogError("error during processing answer"); + } + JSValueRef errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + cbm->callOnError(errorObject); +} + +void CalendarResponseDispatcher::OnAnswerReceived(const IEventAddEventsPtr &event) +{ + LogDebug("entered"); + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + Try + { + if (!cbm) { + LogDebug("no callback manager"); + return; + } + if (event->getResult()) { + LogDebug("result success"); + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(cbm->getContext()); + cbm->callOnSuccess(converter->toJSValueRef(event->getEvents())); + return; + } + LogDebug("result fail"); + } + Catch(ConversionException) + { + LogError("cannot convert event"); + } + JSValueRef errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + cbm->callOnError(errorObject); +} + +void CalendarResponseDispatcher::onAnswerReceived(const OnAddEventsChangedPtr& event) +{ + LogDebug("entered"); + CalendarEventsCallbackPrivateDataPtr multiCallbacks = + DPL::StaticPointerCast(event->getPrivateData()); + JSContextRef context = multiCallbacks->getOnEvent()->getContext(); + + switch (event->getStatus()) + { + case OnAddEventsChanged::EVENT_ADD_SUCCESS: + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + multiCallbacks->getOnEvent()->callOnSuccess(converter->toJSValueRefItem(event->getEvent())); + break; + } + case OnAddEventsChanged::EVENT_ADD_FAIL: + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + JSValueRef errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + context, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + JSValueRef eventObject = converter->toJSValueRefItem(event->getEvent()); + JSValueRef obj[] = {errorObject, eventObject}; + multiCallbacks->getOnEvent()->callOnError(obj, 2); + break; + } + default: + { + LogDebug("Invalid status!"); + JSValueRef errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + context, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + multiCallbacks->getOnEvent()->callOnError(errorObject); + break; + } + } +} + +void CalendarResponseDispatcher::OnAnswerReceived(const IEventUpdateEventsPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + if (!cbm) { + LogDebug("no callback manager"); + return; + } + if (event->getResult()) { + cbm->callOnSuccess(); + } else { + JSValueRef errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + cbm->callOnError(errorObject); + } +} + +void CalendarResponseDispatcher::onAnswerReceived(const OnUpdateEventsChangedPtr& event) +{ + LogDebug("entered"); + CalendarEventsCallbackPrivateDataPtr multiCallbacks = + DPL::StaticPointerCast(event->getPrivateData()); + JSContextRef context = multiCallbacks->getOnEvent()->getContext(); + + switch (event->getStatus()) + { + case OnUpdateEventsChanged::EVENT_UPDATE_SUCCESS: + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + multiCallbacks->getOnEvent()->callOnSuccess(converter->toJSValueRefItem(event->getEvent())); + break; + } + case OnUpdateEventsChanged::EVENT_UPDATE_FAIL: + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + JSValueRef errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + context, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + JSValueRef eventObject = converter->toJSValueRefItem(event->getEvent()); + JSValueRef obj[] = {errorObject, eventObject}; + multiCallbacks->getOnEvent()->callOnError(obj, 2); + break; + } + default: + { + LogDebug("Invalid status!"); + JSValueRef errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + context, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + multiCallbacks->getOnEvent()->callOnError(errorObject); + break; + } + } +} + +void CalendarResponseDispatcher::OnAnswerReceived(const IEventDeleteEventsPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + if (!cbm) { + LogDebug("no callback manager"); + return; + } + if (event->getResult()) { + cbm->callOnSuccess(); + } else { + JSValueRef errorObject; + if (event->getExceptionCode() == + ExceptionCodes::NotFoundException) { + errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::NOT_FOUND_ERROR); + } else { + errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + cbm->callOnError(errorObject); + } +} + +void CalendarResponseDispatcher::onAnswerReceived(const OnDeleteEventsChangedPtr& event) +{ + LogDebug("entered"); + CalendarEventsCallbackPrivateDataPtr multiCallbacks = + DPL::StaticPointerCast(event->getPrivateData()); + JSContextRef context = multiCallbacks->getOnEvent()->getContext(); + + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + + switch (event->getStatus()) + { + case OnDeleteEventsChanged::EVENT_DELETE_SUCCESS: + { + multiCallbacks->getOnEvent()->callOnSuccess( + converter->toJSValueRef(event->getEventId())); + break; + } + case OnDeleteEventsChanged::EVENT_DELETE_FAIL: + { + JSValueRef errorObject; + if (event->getExceptionCode() == ExceptionCodes::NotFoundException) { + + errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + context, TizenApis::Commons::JSTizenException::NOT_FOUND_ERROR); + } else { + errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + context, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + JSValueRef eventObject = converter->toJSValueRef(event->getEventId()); + JSValueRef obj[] = {errorObject, eventObject}; + multiCallbacks->getOnEvent()->callOnError(obj, 2); + break; + } + default: + { + LogDebug("Invalid status!"); + JSValueRef errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + context, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + multiCallbacks->getOnEvent()->callOnError(errorObject); + break; + } + } +} + +void CalendarResponseDispatcher::OnAnswerReceived(const IEventFindEventsPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + if (!cbm) { + LogError("no callback manager"); + return; + } + Try + { + if (event->getResult()) { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(cbm->getContext()); + + JSValueRef result = converter->toJSValueRef(event->getEvents()); + cbm->callOnSuccess(result); + return; + } else { + JSValueRef errorObject; + if (event->getExceptionCode() == + ExceptionCodes::NotFoundException) { + errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } else { + errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + cbm->callOnError(errorObject); + } + } + Catch(Exception) + { + LogError("error during processing answer"); + } + JSValueRef errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + cbm->callOnError(errorObject); +} + +void CalendarResponseDispatcher::OnAnswerReceived(const IEventExpandEventRecurrencePtr &event) +{ + LogDebug("entered"); + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + Try + { + if (!cbm) { + LogDebug("no callback manager"); + return; + } + if (event->getResult()) { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(cbm->getContext()); + cbm->callOnSuccess(converter->toJSValueRef(event->getExpandedEventList())); + return; + } else { + JSValueRef errorObject; + if (event->getExceptionCode() == + ExceptionCodes::NotFoundException) { + errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::NOT_FOUND_ERROR); + } else { + errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + cbm->callOnError(errorObject); + } + LogDebug("result fail"); + } + Catch(ConversionException) + { + LogError("cannot convert event"); + } + JSValueRef errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + cbm->callOnError(errorObject); +} + +void CalendarResponseDispatcher::onAnswerReceived(const OnEventsChangedPtr& event) +{ + LogDebug("entered"); + CalendarChangeCallbackPrivateDataPtr multiCallbacks = + DPL::StaticPointerCast(event->getPrivateData()); + JSContextRef context = multiCallbacks->getOnAdded()->getContext(); + + CalendarConverterFactory::ConverterType converter = CalendarConverterFactory::getConverter(context); + + Try + { + switch (event->getStatus()) + { + case OnEventsChanged::ON_ADD: + { + multiCallbacks->getOnAdded()->callOnSuccess(converter->toJSValueRef(event->getEventList())); + break; + } + case OnEventsChanged::ON_UPDATE: + { + multiCallbacks->getOnUpdated()->callOnSuccess(converter->toJSValueRef(event->getEventList())); + break; + } + case OnEventsChanged::ON_DELETE: + { + CalendarEventListPtr eventList = event->getEventList(); + + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + if (NULL == jsResult) { + ThrowMsg(ConversionException, "Could not create js array object"); + } + + for (std::size_t i = 0; i < eventList->size(); i++) { + EventIdPtr eventId( new EventId() ); + eventId->setUId(eventList->at(i)->getUId()); + eventId->setRecurrenceId(eventList->at(i)->getRecurrenceId()); + JSValueRef tmpVal = converter->toJSValueRef(eventId); + if (!JSSetArrayElement(context, jsResult, i, tmpVal)) { + ThrowMsg(ConversionException, "Could not create js array element"); + } + } + + multiCallbacks->getOnDeleted()->callOnSuccess(jsResult); + break; + } + //case OnEventsChanged::ON_CALENDAR_RESET: + default: + { + LogDebug("Invalid status!"); + JSValueRef errorObject = TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + context, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + multiCallbacks->getOnAdded()->callOnError(errorObject); + break; + } + } + } + Catch(ConversionException) + { + LogError("cannot convert change event"); + } + Catch(Exception) + { + LogError("exception occurred while handling change noti callback!"); + } +} + +} +} +} diff --git a/src/standards/Tizen/Calendar/CalendarResponseDispatcher.h b/src/standards/Tizen/Calendar/CalendarResponseDispatcher.h new file mode 100755 index 0000000..aac2267 --- /dev/null +++ b/src/standards/Tizen/Calendar/CalendarResponseDispatcher.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _CALENDAR_RESPONSEDISPATCHER_H_ +#define _CALENDAR_RESPONSEDISPATCHER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +typedef WrtDeviceApis::Commons::EventAnswerReceiver +GetCalendarsEventAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver +CalendarEventsEventAnswerReceiverAdds; +typedef WrtDeviceApis::Commons::EventAnswerReceiver +CalendarEventsEventAnswerReceiverDeletes; +typedef WrtDeviceApis::Commons::EventAnswerReceiver +CalendarEventsEventAnswerReceiverUpdates; +typedef WrtDeviceApis::Commons::EventAnswerReceiver +CalendarEventsEventAnswerReceiverFind; +typedef WrtDeviceApis::Commons::EventAnswerReceiver +CalendarEventsEventAnswerReceiverExpand; +typedef WrtDeviceApis::Commons::EventListener +OnAddEventsChangedListener; +typedef WrtDeviceApis::Commons::EventListener +OnUpdateEventsChangedListener; +typedef WrtDeviceApis::Commons::EventListener +OnDeleteEventsChangedListener; +typedef WrtDeviceApis::Commons::EventListener +OnEventsChangedListener; + +class CalendarResponseDispatcher : + public GetCalendarsEventAnswerReceiver, + public CalendarEventsEventAnswerReceiverAdds, + public CalendarEventsEventAnswerReceiverDeletes, + public CalendarEventsEventAnswerReceiverUpdates, + public CalendarEventsEventAnswerReceiverFind, + public CalendarEventsEventAnswerReceiverExpand, + public OnAddEventsChangedListener, + public OnUpdateEventsChangedListener, + public OnDeleteEventsChangedListener, + public OnEventsChangedListener +{ + public: + static CalendarResponseDispatcher& getInstance(); + void onAnswerReceived(const TizenApis::Api::Calendar::OnAddEventsChangedPtr& event); + void onAnswerReceived(const TizenApis::Api::Calendar::OnUpdateEventsChangedPtr& event); + void onAnswerReceived(const TizenApis::Api::Calendar::OnDeleteEventsChangedPtr& event); + void onAnswerReceived(const TizenApis::Api::Calendar::OnEventsChangedPtr& event); + private: + CalendarResponseDispatcher(); + virtual ~CalendarResponseDispatcher(); + protected: + void OnAnswerReceived(const TizenApis::Api::Calendar::IEventGetCalendarsPtr &event); + void OnAnswerReceived(const TizenApis::Api::Calendar::IEventAddEventsPtr &event); + void OnAnswerReceived(const TizenApis::Api::Calendar::IEventDeleteEventsPtr &event); + void OnAnswerReceived(const TizenApis::Api::Calendar::IEventUpdateEventsPtr &event); + void OnAnswerReceived(const TizenApis::Api::Calendar::IEventFindEventsPtr &event); + void OnAnswerReceived(const TizenApis::Api::Calendar::IEventExpandEventRecurrencePtr &event); +}; + +} +} +} + +#endif /* _CALENDAR_RESPONSEDISPATCHER_H_ */ diff --git a/src/standards/Tizen/Calendar/JSAttendee.cpp b/src/standards/Tizen/Calendar/JSAttendee.cpp new file mode 100755 index 0000000..1db4ed7 --- /dev/null +++ b/src/standards/Tizen/Calendar/JSAttendee.cpp @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "JSAttendee.h" +#include +#include +#include +#include +#include "CalendarConverter.h" + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +#define TIZEN_ATTENDEE_ATTRIBUTENAME "Attendee" +#define TIZEN_ATTENDEE_NAME "name" +#define TIZEN_ATTENDEE_URI "uri" +#define TIZEN_ATTENDEE_ROLE "role" +#define TIZEN_ATTENDEE_STATUS "status" +#define TIZEN_ATTENDEE_RSVP "RSVP" +#define TIZEN_ATTENDEE_TYPE "type" +#define TIZEN_ATTENDEE_GROUP "group" +#define TIZEN_ATTENDEE_DELEGATORURI "delegatorURI" +#define TIZEN_ATTENDEE_DELEGATEURI "delegateURI" +#define TIZEN_ATTENDEE_UID "uid" + +JSClassDefinition JSAttendee::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_ATTENDEE_ATTRIBUTENAME, + 0, + m_property, + NULL, //m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSAttendee::m_property[] = { + { TIZEN_ATTENDEE_NAME, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_ATTENDEE_URI, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_ATTENDEE_ROLE, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_ATTENDEE_STATUS, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_ATTENDEE_RSVP, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_ATTENDEE_TYPE, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_ATTENDEE_GROUP, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_ATTENDEE_DELEGATORURI, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_ATTENDEE_DELEGATEURI, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_ATTENDEE_UID, getProperty, setProperty, kJSPropertyAttributeNone }, + + { 0, 0, 0, 0 } +}; + +JSClassRef JSAttendee::m_jsClassRef = JSClassCreate( + JSAttendee::getClassInfo()); + +const JSClassDefinition* JSAttendee::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSAttendee::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +JSObjectRef JSAttendee::createJSAttendee(JSContextRef context, EventAttendeePtr attendee) +{ + AttendeePrivateObject *priv = new AttendeePrivateObject(context, attendee); + return JSObjectMake(context, getClassRef(), priv); +} + +void JSAttendee::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("enter"); +} + +void JSAttendee::finalize(JSObjectRef object) +{ + LogDebug("enter"); + AttendeePrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +JSValueRef JSAttendee::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + Try + { + AttendeePrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + EventAttendeePtr attendee = priv->getObject(); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_NAME)) { + return converter->toJSValueRef(attendee->getName()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_URI)) { + return converter->toJSValueRef(attendee->getURI()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_ROLE)) { + return converter->toJSValueRef(converter->toTizenValue(attendee->getRole())); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_STATUS)) { + return converter->toJSValueRef(converter->toTizenValue(attendee->getStatus())); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_RSVP)) { + return converter->toJSValueRef(attendee->getRSVP()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_TYPE)) { + return converter->toJSValueRef(converter->toTizenValue(attendee->getType())); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_GROUP)) { + return converter->toJSValueRef(attendee->getGroup()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_DELEGATORURI)) { + return converter->toJSValueRef(attendee->getDelegatorURI()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_DELEGATEURI)) { + return converter->toJSValueRef(attendee->getDelegateURI()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_UID)) { + return converter->toJSValueRef(attendee->getPersonId()); + } + } + Catch(Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSAttendee::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + Try + { + AttendeePrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + EventAttendeePtr attendee = priv->getObject(); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_NAME)) { + std::string name = converter->toString(value); + attendee->setName(name); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_URI)) { + std::string uri = converter->toString(value); + attendee->setURI(uri); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_ROLE)) { + std::string role = converter->toString(value); + attendee->setRole(converter->toEventAttendeeRole(role)); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_STATUS)) { + std::string status = converter->toString(value); + attendee->setStatus(converter->toEventAttendeeStatus(status)); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_RSVP)) { + bool RSVP = converter->toBool(value); + attendee->setRSVP(RSVP); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_TYPE)) { + std::string type = converter->toString(value); + attendee->setType(converter->toEventAttendeeType(type)); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_GROUP)) { + std::string group = converter->toString(value); + attendee->setGroup(group); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_DELEGATORURI)) { + std::string delegatorURI = converter->toString(value); + attendee->setDelegatorURI(delegatorURI); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_DELEGATEURI)) { + std::string delegateURI = converter->toString(value); + attendee->setDelegateURI(delegateURI); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ATTENDEE_UID)) { + std::string uid = converter->toString(value); + attendee->setPersonId(uid); + return true; + } + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +} +} +} diff --git a/src/standards/Tizen/Calendar/JSAttendee.h b/src/standards/Tizen/Calendar/JSAttendee.h new file mode 100755 index 0000000..54ea2a9 --- /dev/null +++ b/src/standards/Tizen/Calendar/JSAttendee.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _JS_ATTENDEE_H_ +#define _JS_ATTENDEE_H_ + +#include +#include +#include +#include +#include +#include + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +typedef PrivateObject AttendeePrivateObject; + +class JSAttendee +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createJSAttendee(JSContextRef context, Api::Calendar::EventAttendeePtr event); + + private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSClassRef m_jsClassRef; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} +} +} + +#endif /* _JS_ATTENDEE_H_ */ diff --git a/src/standards/Tizen/Calendar/JSCalendar.cpp b/src/standards/Tizen/Calendar/JSCalendar.cpp new file mode 100755 index 0000000..cb5e79f --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCalendar.cpp @@ -0,0 +1,1348 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "JSCalendarManager.h" +#include "CalendarConverter.h" +#include "JSCalendar.h" +#include "JSCalendarItem.h" +#include "JSCalendarEvent.h" +#include "JSCalendarTask.h" +#include "JSCalendarItemProperties.h" +#include "JSEventId.h" +#include "plugin_config.h" +#include "CalendarResponseDispatcher.h" +#include "CalendarMultiCallback.h" + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Commons; + +namespace { +/** + * @throw InvalidArgumentException If not a callback nor JS null nor JS undefined. + */ +JSValueRef getFunctionOrNull(JSContextRef ctx, + JSValueRef arg) +{ + if (Validator(ctx).isCallback(arg)) { + return arg; + } else if (!JSValueIsNull(ctx, arg) && !JSValueIsUndefined(ctx, arg)) { + ThrowMsg(InvalidArgumentException, "Not a function nor JS null."); + } + return NULL; +} +} + +#define TIZEN_CALENDAR_ATTRIBUTENAME "Calendar" +#define TIZEN_CALENDAR_PROPERTY_NAME "name" +#define TIZEN_CALENDAR_PROPERTY_ACCOUNT_ID "accountId" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +JSClassDefinition JSCalendar::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_CALENDAR_ATTRIBUTENAME, + NULL, + m_property, + m_function, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSCalendar::m_property[] = { + { TIZEN_CALENDAR_PROPERTY_NAME, JSCalendar::getPropertyName, + NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_CALENDAR_PROPERTY_ACCOUNT_ID, JSCalendar::getPropertyAccountId, + NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSCalendar::m_function[] = { + { "add", add, kJSPropertyAttributeNone }, + { "addBatch", addBatch, kJSPropertyAttributeNone }, + { "update", update, kJSPropertyAttributeNone }, + { "updateBatch", updateBatch, kJSPropertyAttributeNone }, + { "remove", remove, kJSPropertyAttributeNone }, + { "removeBatch", removeBatch, kJSPropertyAttributeNone }, + { "find", find, kJSPropertyAttributeNone }, + { "convertFromString", convertFromString, kJSPropertyAttributeNone }, + { "convertToString", convertToString, kJSPropertyAttributeNone }, + { "addChangeListener", addChangeListener, kJSPropertyAttributeNone }, + { "removeChangeListener", removeChangeListener, kJSPropertyAttributeNone }, + { "expandEventRecurrence", expandEventRecurrence, kJSPropertyAttributeNone }, + + { 0, 0, 0 } +}; + +JSClassRef JSCalendar::m_jsClassRef = JSClassCreate(JSCalendar::getClassInfo()); + +void JSCalendar::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("entered"); + CalendarPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + //create default instance + LogWarning("create default instance"); + ICalendarPtr calendar = + Api::Calendar::CalendarFactory::getInstance().createCalendarObject(); + priv = new CalendarPrivObject(context, calendar); + if (!JSObjectSetPrivate(object, static_cast(priv))) { + delete priv; + } + } else { + //can be set by JSMakeObject inside getCalendars method + LogDebug("private object alrerady exists"); + } +} + +void JSCalendar::finalize(JSObjectRef object) +{ + LogDebug("entered"); + CalendarPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; +} + +const JSClassRef JSCalendar::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSCalendar::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSCalendar::add(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + + CalendarPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + assert(privateObject); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(privateObject->getContext(), CALENDAR_FUNCTION_API_ADD); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try + { + ICalendarPtr calendar = getCalendar(context, thisObject, NULL); + + if (argumentCount > 1) { + LogError("Wrong number of parameters."); + Throw(InvalidArgumentException); + } + + if (JSValueIsUndefined(context, arguments[0]) || + JSValueIsNull(context, arguments[0])) { + Throw(InvalidArgumentException); + } + + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(privateObject->getContext()); + CalendarEventPtr event = converter->toEvent(arguments[0]); + if (!event) { + LogError("Failed to get an event."); + Throw(UnknownException); + } + + IEventAddEventPtr dplEvent(new IEventAddEvent()); + dplEvent->setEvent(event); + dplEvent->setForSynchronousCall(); + calendar->addEvent(dplEvent); + + if (dplEvent->getResult()) { + return converter->toJSValueRefItem(dplEvent->getEvent()); + } else { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + } + Catch(UnsupportedException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::NOT_SUPPORTED_ERROR); + } + Catch(InvalidArgumentException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendar::addBatch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + + CalendarPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + assert(privateObject); + + JSCallbackManagerPtr cbm(NULL); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(privateObject->getContext(), CALENDAR_FUNCTION_API_ADD_BATCH); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try + { + ICalendarPtr calendar = getCalendar(context, thisObject, NULL); + + if (argumentCount > 3) { + LogError("Wrong number of parameters"); + Throw(InvalidArgumentException); + } + + CalendarConverterFactory::ConverterType converter = CalendarConverterFactory::getConverter(context); + + CalendarEventListPtr events; + if (JSValueIsUndefined(context, arguments[0]) || JSValueIsNull(context, arguments[0])) { + Throw(InvalidArgumentException); + } + events = converter->toVectorOfEventsFromProperty(arguments[0]); + if (!events) { + LogError("Failed to create events."); + Throw(InvalidArgumentException); + } + + JSValueRef onError = NULL; + if (argumentCount > 2) { + onError = getFunctionOrNull(context, arguments[2]); + } + JSContextRef globalContext = privateObject->getContext(); + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext, NULL, onError); + CalendarEventsSuccessCallback result; + //result.onSuccess = JSUtils::getJSPropertyOrUndefined(context, objectCallbacks, "onSuccess"); + result.onSuccess = arguments[1]; + Validator validator(context); + if ((!validator.isNullOrUndefined(result.onSuccess) && !validator.isCallback(result.onSuccess))) + { + LogError("Calendar callback set error."); + Throw(InvalidArgumentException); + } + cbm->setOnSuccess(result.onSuccess); + //JSCallbackManagerPtr onAddEventCbm = JSCallbackManager::createObject(globalContext, result.onEventSuccess, result.onEventError); + //onAddEventCbm->setObject(thisObject); + + LogDebug("Proceed the event to the platform."); + + //CalendarEventsCallbackPrivateDataPtr privData(new CalendarEventsCallbackPrivateData(cbm, onAddEventCbm)); + //OnAddEventsChangedEmitterPtr emitter(new OnAddEventsChangedEmitter()); + //emitter->setListener(&CalendarResponseDispatcher::getInstance()); + //emitter->setEventPrivateData(DPL::StaticPointerCast(privData)); + //calendar->setAddEmitter(emitter); + + IEventAddEventsPtr dplEvent(new IEventAddEvents()); + dplEvent->setEvents(events); + dplEvent->setPrivateData(DPL::StaticPointerCast(cbm)); + dplEvent->setForAsynchronousCall(&CalendarResponseDispatcher::getInstance()); + calendar->addEvents(dplEvent); + + return JSValueMakeNull(context); + } + Catch(UnsupportedException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::NOT_SUPPORTED_ERROR); + } + Catch(InvalidArgumentException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + if (NULL != cbm) { + cbm->callOnError(TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::UNKNOWN_ERROR)); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendar::update(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + + CalendarPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + assert(privateObject); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(privateObject->getContext(), CALENDAR_FUNCTION_API_UPDATE); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try + { + ICalendarPtr calendar = getCalendar(context, thisObject, exception); + + if (argumentCount>2) { + LogError("Wrong number of parameters."); + Throw(InvalidArgumentException); + } + + if (JSValueIsUndefined(context, arguments[0]) || + JSValueIsNull(context, arguments[0])) { + Throw(ConversionException); + } else if (!JSValueIsObjectOfClass(context, arguments[0], JSCalendarItem::getClassRef())) { + LogError("Item parameter is not a type of item class."); + Throw(InvalidArgumentException); + } + + JSObjectRef arg = JSValueToObject(context, arguments[0], exception); + CalendarEventPtr event = JSCalendarItem::getPrivateObject(arg); + if (!JSCalendarItem::validate(context, arg, exception)) { + LogError("Event parameter contains errors."); + Throw(ConversionException); + } + if (!event) { + LogError("Failed to get event."); + Throw(UnknownException); + } + + bool updateAllInstances = true; + CalendarConverterFactory::ConverterType converter = CalendarConverterFactory::getConverter(context); + if( argumentCount > 1 ) { + if (JSValueIsBoolean(context, arguments[1])) { + updateAllInstances = converter->toBool(arguments[1]); + } else { + LogInfo("updateAllInstances is wrong!"); + Throw(InvalidArgumentException); + } + } + + IEventUpdateEventPtr dplEvent(new IEventUpdateEvent()); + dplEvent->setEvent(event); + dplEvent->setUpdateAllInstances(updateAllInstances); + dplEvent->setForSynchronousCall(); + calendar->updateEvent(dplEvent); + + if (dplEvent->getResult()) { + return JSValueMakeNull(context); + } else { + LogError("Unknow error occured."); + Throw(UnknownException); + } + } + Catch(InvalidArgumentException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendar::updateBatch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + + CalendarPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + assert(privateObject); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(privateObject->getContext(), CALENDAR_FUNCTION_API_UPDATE_BATCH); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + JSCallbackManagerPtr cbm(NULL); + + Try + { + ICalendarPtr calendar = getCalendar(context, thisObject, exception); + + if (argumentCount > 4) { + LogError("Wrong callbacks parameters"); + Throw(InvalidArgumentException); + } + + CalendarConverterFactory::ConverterType converter = CalendarConverterFactory::getConverter(context); + + if (JSValueIsUndefined(context, arguments[0]) || JSValueIsNull(context, arguments[0])) { + Throw(InvalidArgumentException); + } + + CalendarEventListPtr events; + events = converter->toVectorOfEvents(arguments[0]); + if (!events) { + LogError("Failed to get events"); + Throw(UnknownException); + } + + JSValueRef onError = NULL; + if (argumentCount > 2) { + onError = getFunctionOrNull(context, arguments[2]); + } + JSContextRef globalContext = privateObject->getContext(); + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext, NULL, onError); + CalendarEventsSuccessCallback result; + result.onSuccess = arguments[1]; + Validator validator(context); + if ((!validator.isNullOrUndefined(result.onSuccess) && !validator.isCallback(result.onSuccess))) + { + LogError("Calendar callback set error."); + Throw(InvalidArgumentException); + } + cbm->setOnSuccess(result.onSuccess); + + bool updateAllInstances = true; + if( argumentCount > 3 ) { + if (JSValueIsBoolean(context, arguments[3])) { + updateAllInstances = converter->toBool(arguments[3]); + } else { + LogInfo("updateAllInstances is wrong!"); + Throw(InvalidArgumentException); + } + } + + LogDebug("Proceed the event to the platform."); + + IEventUpdateEventsPtr dplEvent(new IEventUpdateEvents()); + dplEvent->setEvents(events); + dplEvent->setUpdateAllInstances(updateAllInstances); + dplEvent->setPrivateData(DPL::StaticPointerCast(cbm)); + dplEvent->setForAsynchronousCall(&CalendarResponseDispatcher::getInstance()); + calendar->updateEvents(dplEvent); + + return makePendingOperation(cbm->getContext(), dplEvent); + } + Catch(InvalidArgumentException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + if (NULL != cbm) { + cbm->callOnError(TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::UNKNOWN_ERROR)); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendar::remove(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + assert(privateObject); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(privateObject->getContext(), CALENDAR_FUNCTION_API_REMOVE); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try + { + ICalendarPtr calendar = getCalendar(context, thisObject, exception); + + if (argumentCount>1) { + LogError("Wrong number of parameters."); + Throw(InvalidArgumentException); + } + + if (JSValueIsUndefined(context, arguments[0]) || + JSValueIsNull(context, arguments[0])) { + Throw(InvalidArgumentException); + } + + if (!JSValueIsObjectOfClass(context, arguments[0], JSEventId::getClassRef())) { + LogError("Wrong event id parameter."); + Throw(InvalidArgumentException); + } + + EventIdPtr itemId; + CalendarConverterFactory::ConverterType converter = CalendarConverterFactory::getConverter(context); + itemId = converter->toEventId(arguments[0]); + + IEventDeleteEventPtr dplEvent(new IEventDeleteEvent()); + dplEvent->setEventId(itemId); + dplEvent->setForSynchronousCall(); + calendar->deleteEvent(dplEvent); + + if (dplEvent->getResult()) { + LogInfo("Successfully deleted."); + return JSValueMakeNull(context); + } else { + if (dplEvent->getExceptionCode() == ExceptionCodes::NotFoundException) { + LogError("Not found exception."); + Throw(NotFoundException); + } else { + LogError("Unknow error occured."); + Throw(UnknownException); + } + } + } + Catch(InvalidArgumentException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch (NotFoundException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::NOT_FOUND_ERROR); + } + Catch(Exception) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendar::removeBatch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + assert(privateObject); + + JSCallbackManagerPtr cbm(NULL); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(privateObject->getContext(), CALENDAR_FUNCTION_API_REMOVE_BATCH); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try + { + ICalendarPtr calendar = getCalendar(context, thisObject, exception); + + if (argumentCount > 3) { + LogError("No callback parameters"); + Throw(InvalidArgumentException); + } + + CalendarConverterFactory::ConverterType converter = CalendarConverterFactory::getConverter(context); + + if (JSValueIsUndefined(context, arguments[0]) || JSValueIsNull(context, arguments[0])) { + Throw(InvalidArgumentException); + } + + EventIdListPtr itemIds; + itemIds = converter->toVectorOfEventIds(arguments[0]); + + JSValueRef onError = NULL; + if (argumentCount > 2) { + onError = getFunctionOrNull(context, arguments[2]); + } + JSContextRef globalContext = privateObject->getContext(); + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext, NULL, onError); + CalendarEventsSuccessCallback result; + result.onSuccess = arguments[1]; + Validator validator(context); + if ((!validator.isNullOrUndefined(result.onSuccess) && !validator.isCallback(result.onSuccess))) + { + LogError("Calendar callback set error."); + Throw(InvalidArgumentException); + } + cbm->setOnSuccess(result.onSuccess); + + LogDebug("Proceed the event to the platform."); + + IEventDeleteEventsPtr dplEvent(new IEventDeleteEvents()); + dplEvent->setEventIds(itemIds); + dplEvent->setPrivateData(DPL::StaticPointerCast(cbm)); + dplEvent->setForAsynchronousCall(&CalendarResponseDispatcher::getInstance()); + calendar->deleteEvents(dplEvent); + + return makePendingOperation(cbm->getContext(), dplEvent); + } + Catch(InvalidArgumentException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + if (NULL != cbm) { + cbm->callOnError(TizenApis::Commons::JSTizenExceptionFactory::makeErrorObject( + cbm->getContext(), TizenApis::Commons::JSTizenException::UNKNOWN_ERROR)); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendar::find(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + assert(privateObject); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(privateObject->getContext(), CALENDAR_FUNCTION_API_FIND); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + JSCallbackManagerPtr cbm(NULL); + Try + { + ICalendarPtr calendar = getCalendar(context, thisObject, exception); + if (argumentCount < 1) { + LogError("No callback parameters"); + Throw(InvalidArgumentException); + } + JSValueRef onError = + (argumentCount > + 1 ? getFunctionOrNull(context, arguments[1]) : NULL); + JSContextRef globalContext = privateObject->getContext(); + cbm = JSCallbackManager::createObject(globalContext, NULL, onError); + + Validator validator(context); + if (validator.isCallback(arguments[0])) { + cbm->setOnSuccess(arguments[0]); + } else if (JSValueIsNull(context, + arguments[0]) || + JSValueIsUndefined(context, arguments[0])) { + Throw(ConversionException); + } else { + Throw(InvalidArgumentException); + } + //setup filters + EventFilterPtr filter(NULL); + if (argumentCount >= 3) { + LogDebug("setting some filters"); + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + Try + { + if (!JSValueIsUndefined(context, arguments[2]) && + !JSValueIsNull(context, arguments[2])) { + filter = converter->toEventFilter(arguments[2]); + } + } + Catch(InvalidArgumentException) + { + LogError("Invalid argument"); + filter.Reset(); + } + } + IEventFindEventsPtr dplEvent(new IEventFindEvents()); + dplEvent->setPrivateData(DPL::StaticPointerCast(cbm)); + dplEvent->setForAsynchronousCall(&CalendarResponseDispatcher::getInstance()); + dplEvent->setFilter(filter); + calendar->findEvents(dplEvent); + + return JSValueMakeNull(context); + } + Catch(InvalidArgumentException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendar::findEventsGeneric(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + + CalendarPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + assert(privateObject); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(privateObject->getContext(), CALENDAR_FUNCTION_API_FIND); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + JSCallbackManagerPtr cbm(NULL); + + Validator validator(context, exception); + CalendarConverterFactory::ConverterType converter = CalendarConverterFactory::getConverter(context); + TizenApis::Tizen1_0::Tizen::FilterConverterFactory::ConverterType filterConverter = TizenApis::Tizen1_0::Tizen::FilterConverterFactory::getConverter(context); + ICalendarPtr calendar = getCalendar(context, thisObject, exception); + + JSContextRef globalContext = privateObject->getContext(); + cbm = JSCallbackManager::createObject(globalContext); + + Try + { + if (argumentCount == 0 || + (!validator.isCallback(arguments[0])) || + (argumentCount >= 2 && (!validator.isCallback(arguments[1]))) || + (argumentCount >= 3 && (!JSValueIsObject(context, arguments[2]) && !validator.isNullOrUndefined(arguments[2]))) || + (argumentCount >= 4 && (!JSValueIsObject(context, arguments[3]) && !validator.isNullOrUndefined(arguments[3]))) || + (argumentCount >= 5 && (!JSIsArrayValue(context, arguments[4]) && !validator.isNullOrUndefined(arguments[4])))) { + LogDebug("Argument type mismatch"); + Throw(InvalidArgumentException); + } + + if (cbm) { + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + onSuccessForCbm = arguments[0]; + if (argumentCount >= 2) { + onErrorForCbm = arguments[1]; + } + cbm->setObject(thisObject); + cbm->setOnSuccess(onSuccessForCbm); + cbm->setOnError(onErrorForCbm); + } + + IEventFindEventsPtr dplEvent(new IEventFindEvents()); + dplEvent->setPrivateData(DPL::StaticPointerCast(cbm)); + dplEvent->setForAsynchronousCall(&CalendarResponseDispatcher::getInstance()); + + if (argumentCount >= 3 && !validator.isNullOrUndefined(arguments[2])) { + dplEvent->setGenericFilter(filterConverter->toFilter(arguments[2])); + } + if (argumentCount >= 4 && !validator.isNullOrUndefined(arguments[3])) { + // dplEvent->setSortModes(filterConverter->toSortModeArray(arguments[3])); + TizenApis::Api::Tizen::SortModeArrayPtr sortModes(new TizenApis::Api::Tizen::SortModeArray()); + sortModes->push_back(filterConverter->toSortMode(arguments[3])); + dplEvent->setSortModes(sortModes); + } + if (argumentCount >= 5 && !validator.isNullOrUndefined(arguments[4])) { + dplEvent->setAttributesOfInterest(converter->toVectorOfStrings(arguments[4])); + } + + calendar->findEvents(dplEvent); + } + Catch(InvalidArgumentException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendar::expandEventRecurrence(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + assert(privateObject); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(privateObject->getContext(), CALENDAR_FUNCTION_API_EXPAND_EVENT_RECURRENCE); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + JSCallbackManagerPtr cbm(NULL); + + Try + { + ICalendarPtr calendar = getCalendar(context, thisObject, exception); + if (argumentCount>5) { + LogError("Wrong number of parameters."); + Throw(InvalidArgumentException); + } + + JSValueRef onError =(argumentCount > 4 ? getFunctionOrNull(context, arguments[4]) : NULL); + JSContextRef globalContext = privateObject->getContext(); + cbm = JSCallbackManager::createObject(globalContext, NULL, onError); + + Validator validator(context); + if (validator.isCallback(arguments[3])) { + cbm->setOnSuccess(arguments[3]); + } else if (JSValueIsNull(context, + arguments[3]) || + JSValueIsUndefined(context, arguments[3])) { + Throw(InvalidArgumentException); + } else { + Throw(InvalidArgumentException); + } + + JSObjectRef arg = JSValueToObject(context, arguments[0], exception); + CalendarEventPtr event = JSCalendarItem::getPrivateObject(arg); + if (!event) { + LogError("Failed to get an event."); + Throw(UnknownException); + } + + std::time_t startDate = 0; + std::time_t endDate = INT_MAX; // about 60 years in 4 bytes system. + Converter converter(context); + TimeUtilConverter timeConverter(context); + if (argumentCount>1 ) { + startDate = timeConverter.toTZDateTimeT(arguments[1]); + } + if (argumentCount>2 ) { + endDate = timeConverter.toDateTimeT(arguments[2]); + } + + IEventExpandEventRecurrencePtr dplEvent(new IEventExpandEventRecurrence()); + dplEvent->setPrivateData(DPL::StaticPointerCast(cbm)); + dplEvent->setForAsynchronousCall(&CalendarResponseDispatcher::getInstance()); + dplEvent->setEvent(event); + dplEvent->setStartDate(startDate); + dplEvent->setEndDate(endDate); + calendar->expandEventRecurrence(dplEvent); + + return JSValueMakeNull(context); + } + Catch(InvalidArgumentException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendar::convertFromString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + + CalendarPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + assert(privateObject); + + JSContextRef globalContext = privateObject->getContext(); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(globalContext, CALENDAR_FUNCTION_API_CONVERT_FROM_STRING); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try + { + ICalendarPtr calendar = getCalendar(context, thisObject, NULL); + if (argumentCount>2 || argumentCount<1) { + LogError("Wrong count of parameters"); + Throw(InvalidArgumentException); + } + + if (JSValueIsUndefined(context, arguments[0]) || + JSValueIsNull(context, arguments[0])) { + Throw(InvalidArgumentException); + } + else if (!JSValueIsString(context, arguments[0])) { + LogError("invalid type of id parameter"); + Throw(InvalidArgumentException); + } + + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + + std::string eventStr; + CalendarEvent::VObjectFormat format = CalendarEvent::ICALENDAR_20; + + if (JSValueIsString(context, arguments[0])) { + eventStr = converter->toString(arguments[0]); + } else { + LogError("Wrong type of itemStr."); + Throw(InvalidArgumentException); + } + + if( argumentCount>1 ) + { + if (JSValueIsString(context, arguments[1])) { + format = converter->toVObjectFormat(converter->toString(arguments[1])); + } else { + LogError("Wrong type of format."); + Throw(InvalidArgumentException); + } + } + + IEventCreateEventFromStringPtr dplEvent(new IEventCreateEventFromString()); + dplEvent->setEventString(eventStr); + dplEvent->setFormat(format); + dplEvent->setForSynchronousCall(); + calendar->createEventFromString(dplEvent); + + if (dplEvent->getResult()) { + LogInfo("Successfully created an event."); + return converter->toJSValueRefItemProperties(dplEvent->getEvent()); + } else { + LogError("Unexpected error."); + Throw(UnknownException); + } + } + Catch(InvalidArgumentException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendar::convertToString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + + CalendarPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + assert(privateObject); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(privateObject->getContext(), + CALENDAR_FUNCTION_API_CONVERT_TO_STRING); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try + { + ICalendarPtr calendar = getCalendar(context, thisObject, NULL); + if (argumentCount>2 || argumentCount<1) { + LogError("Wrong number of parameters."); + Throw(InvalidArgumentException); + } + + if (JSValueIsUndefined(context, arguments[0]) || + JSValueIsNull(context, arguments[0])) { + Throw(ConversionException); + } + + if (CalendarEvent::EVENT_TYPE==calendar->getType()) { + if (!JSValueIsObjectOfClass(context, arguments[0], + JSCalendarItem::getClassRef())) { + LogError("Wrong event argument."); + Throw(InvalidArgumentException); + } + if (!JSCalendarEvent::validate(context, Converter(context).toJSObjectRef( + arguments[0]), NULL)) { + Throw(ConversionException); + } + } else if(CalendarEvent::TASK_TYPE==calendar->getType()) { + if (!JSValueIsObjectOfClass(context, arguments[0], + JSCalendarItem::getClassRef())) { + LogError("Wrong task argument."); + Throw(InvalidArgumentException); + } + if (!JSCalendarTask::validate(context, Converter(context).toJSObjectRef( + arguments[0]), NULL)) { + Throw(ConversionException); + } + } + + JSObjectRef arg = JSValueToObject(context, arguments[0], exception); + CalendarEventPtr event = JSCalendarItem::getPrivateObject(arg); + if (!event) { + LogError("Failed to get an event."); + Throw(UnknownException); + } + + CalendarEvent::VObjectFormat format = CalendarEvent::ICALENDAR_20; + CalendarConverter converter(context); + if( argumentCount>1 ) + { + if (JSValueIsString(context, arguments[1])) { + format = converter.toVObjectFormat(converter.toString(arguments[1])); + } + } + + IEventExportEventToStringPtr dplEvent(new IEventExportEventToString()); + dplEvent->setEvent(event); + dplEvent->setFormat(format); + dplEvent->setForSynchronousCall(); + calendar->exportEventToString(dplEvent); + + if (dplEvent->getResult()) { + return converter.toJSValueRef(dplEvent->getEventString()); + } else { + Throw(UnknownException); + } + } + Catch(InvalidArgumentException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendar::addChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + assert(privateObject); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(privateObject->getContext(), CALENDAR_FUNCTION_API_ADD_CHANGE_LISTENER); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + JSCallbackManagerPtr cbm(NULL); + Try + { + ICalendarPtr calendar = getCalendar(context, thisObject, exception); + if (argumentCount > 2) { + LogError("No callback parameters"); + Throw(InvalidArgumentException); + } + + CalendarConverterFactory::ConverterType converter = CalendarConverterFactory::getConverter(context); + JSValueRef onError = NULL; + if (argumentCount > 1) { + onError = getFunctionOrNull(context, arguments[1]); + } + JSContextRef globalContext = privateObject->getContext(); + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext, NULL, onError); + JSObjectRef objectCallbacks = converter->toJSObjectRef(arguments[0]); + CalendarChangeCallback result; + result.onAdded = JSUtils::getJSPropertyOrUndefined(context, objectCallbacks, "onItemsAdded"); + result.onUpdated = JSUtils::getJSPropertyOrUndefined(context, objectCallbacks, "onItemsUpdated"); + result.onDeleted = JSUtils::getJSPropertyOrUndefined(context, objectCallbacks, "onItemsRemoved"); + Validator validator(context); + if ((!validator.isNullOrUndefined(result.onAdded) && !validator.isCallback(result.onAdded)) || + (!validator.isNullOrUndefined(result.onUpdated) && !validator.isCallback(result.onUpdated)) || + (!validator.isNullOrUndefined(result.onDeleted) && !validator.isCallback(result.onDeleted))) + { + LogError("Calendar multi calback set error!"); + Throw(InvalidArgumentException); + } + JSCallbackManagerPtr onAddedCbm = JSCallbackManager::createObject(globalContext, result.onAdded, NULL); + JSCallbackManagerPtr onUpdatedCbm = JSCallbackManager::createObject(globalContext, result.onUpdated, NULL); + JSCallbackManagerPtr onDeletedCbm = JSCallbackManager::createObject(globalContext, result.onDeleted, NULL); + onAddedCbm->setObject(thisObject); + onUpdatedCbm->setObject(thisObject); + onDeletedCbm->setObject(thisObject); + + /* The interested attributes are not supported in platform. + AttributeListPtr attributes; + if( argumentCount >= 3 ) { + try + { + *attributes = converter->toVectorOfStrings(arguments[2]); + if (!attributes) { + LogError("watchChanges: Failed to get interested attributes"); + Throw(InvalidArgumentException); + } + } + Catch(Exception) + { + LogError("Error while converting the attributes"); + Throw(InvalidArgumentException); + } + }*/ + + LogDebug("Make change emitter and sync operation"); + + CalendarChangeCallbackPrivateDataPtr privData(new CalendarChangeCallbackPrivateData( + onAddedCbm, onUpdatedCbm, onDeletedCbm)); + OnEventsChangedEmitterPtr emitter(new OnEventsChangedEmitter()); + emitter->setListener(&CalendarResponseDispatcher::getInstance()); + emitter->setEventPrivateData(DPL::StaticPointerCast(privData)); + + // return sync operation and process the events and emit results while processing them + IEventWatchChangesPtr dplEvent(new IEventWatchChanges()); + //dplEvent->setAttributes(attributes); + dplEvent->setEmitter(emitter); + dplEvent->setPrivateData(DPL::StaticPointerCast(cbm)); + dplEvent->setForSynchronousCall(); + calendar->watchChanges(dplEvent); + + long watchId; + if (dplEvent->getResult()) { + watchId = dplEvent->getWatchId(); + LogDebug("Returning the watchId "<toJSValueRefLong(watchId); + } else { + LogDebug("Watch failed!"); + Throw(UnknownException); + } + return JSValueMakeNull(context); + } + Catch(InvalidArgumentException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendar::removeChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + assert(privateObject); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(privateObject->getContext(), CALENDAR_FUNCTION_API_REMOVE_CHANGE_LISTENER); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try + { + ICalendarPtr calendar = getCalendar(context, thisObject, exception); + if (argumentCount > 1) { + LogError("Wrong number of parameter."); + Throw(InvalidArgumentException); + } + + long watchId = -1; + CalendarConverterFactory::ConverterType converter = CalendarConverterFactory::getConverter(context); + if (JSValueIsNumber(context, arguments[0])) + watchId = converter->toLong(arguments[0]); + + LogDebug("Make sync operation"); + + IEventClearWatchPtr dplEvent(new IEventClearWatch()); + dplEvent->setWatchId(watchId); + dplEvent->setForSynchronousCall(); + calendar->clearWatch(dplEvent); + + return JSValueMakeNull(context); + } + Catch(InvalidArgumentException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) + { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendar::getPropertyName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + ICalendarPtr calendar = getCalendar(context, object, exception); + Converter converter(context); + return converter.toJSValueRef(calendar->getName()); + } + Catch(Exception) + { + LogError("error during executing a function"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSCalendar::getPropertyAccountId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + ICalendarPtr calendar = getCalendar(context, object, exception); + Converter converter(context); + return converter.toJSValueRefLong(calendar->getAccountId()); + } + Catch(Exception) + { + LogError("error during executing a function"); + } + return JSValueMakeUndefined(context); +} + +ICalendarPtr JSCalendar::getCalendar(JSContextRef ctx, + const JSObjectRef object, + JSValueRef* exception) +{ + CalendarPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (priv) { + return priv->getObject(); + } + ThrowMsg(NullPointerException, "Private object is NULL."); +} + +} +} +} diff --git a/src/standards/Tizen/Calendar/JSCalendar.h b/src/standards/Tizen/Calendar/JSCalendar.h new file mode 100755 index 0000000..4e504f1 --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCalendar.h @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _JS_TIZEN_CALENDAR_H_ +#define _JS_TIZEN_CALENDAR_H_ + +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject CalendarPrivObject; + +class JSCalendar +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + private: + /** + * This member variable contains the values which has to be passed + * when the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to + * the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getPropertyName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyAccountId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * Add a calendar item. + */ + static JSValueRef add(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Add calendar items. + */ + static JSValueRef addBatch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Update an item. + */ + static JSValueRef update(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Update items. + */ + static JSValueRef updateBatch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Remove a calendar item. + */ + static JSValueRef remove(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Remove calendar items. + */ + static JSValueRef removeBatch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Search for calendar events. + */ + static JSValueRef find(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Search for calendar events. + */ + static JSValueRef findEventsGeneric(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Create an event from string + */ + static JSValueRef convertFromString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Export a string from event + */ + static JSValueRef convertToString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Watch changes + */ + static JSValueRef addChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Clear watch + */ + static JSValueRef removeChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Expand event instances from a recurring event + */ + static JSValueRef expandEventRecurrence(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Returns calendar stored as private object + */ + static Api::Calendar::ICalendarPtr getCalendar(JSContextRef ctx, + const JSObjectRef object, + JSValueRef* exception); +}; + +} +} +} + +#endif /* _JS_TIZEN_CALENDAR_H_ */ + diff --git a/src/standards/Tizen/Calendar/JSCalendarEvent.cpp b/src/standards/Tizen/Calendar/JSCalendarEvent.cpp new file mode 100755 index 0000000..e8610ec --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCalendarEvent.cpp @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include "JSCalendarEvent.h" +#include "JSCalendarItemProperties.h" +#include "CalendarConverter.h" +#include "JSEventId.h" +#include +#include + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +#define TIZEN_CALENDAR_EVENT_ATTRIBUTENAME "CalendarEvent" + +#define TIZEN_CALENDAR_EVENT_ID "id" +#define TIZEN_CALENDAR_EVENT_LASTMODIFIEDDATE "lastModificationDate" +#define TIZEN_CALENDAR_EVENT_IS_DETACHED "isDetached" + +JSClassDefinition JSCalendarEvent::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_CALENDAR_EVENT_ATTRIBUTENAME, + JSCalendarItemProperties::getClassRef(), + m_property, + NULL, // m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSCalendarEvent::m_property[] = { + { TIZEN_CALENDAR_EVENT_ID, getPropertyId, + NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_CALENDAR_EVENT_LASTMODIFIEDDATE, getPropertyLastModifiedDate, + NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_CALENDAR_EVENT_IS_DETACHED, getPropertyIsDetached, + NULL, kJSPropertyAttributeReadOnly }, + + { 0, 0, 0, 0 } +}; + +JSClassRef JSCalendarEvent::m_jsClassRef = JSClassCreate(JSCalendarEvent::getClassInfo()); + +void JSCalendarEvent::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("entered"); + CalendarEventPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + CalendarEventPtr privateData(new CalendarEvent()); + priv = new CalendarEventPrivObject(context, privateData); + JSObjectSetPrivate(object, static_cast(priv)); + LogDebug("new event is created"); + } else { + LogDebug("private object already exists"); + } +} + +void JSCalendarEvent::finalize(JSObjectRef object) +{ + LogDebug("entered"); +} + +const JSClassRef JSCalendarEvent::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSCalendarEvent::getClassInfo() +{ + return &m_classInfo; +} + +CalendarEventPtr JSCalendarEvent::getPrivateObject(JSObjectRef object) +{ + LogDebug("entered"); + CalendarEventPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object is null"); + } + CalendarEventPtr result = priv->getObject(); + if (!result) { + ThrowMsg(NullPointerException, "Private object is null"); + } + return result; +} + +void JSCalendarEvent::setPrivateObject(const CalendarEventPtr &event, + JSContextRef ctx, + const JSObjectRef object) +{ + LogDebug("entered"); + Try + { + CalendarEventPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + priv = new CalendarEventPrivObject(ctx, event); + if (!JSObjectSetPrivate(object, static_cast(priv))) { + delete priv; + } + } + Catch(Exception) + { + LogError("Error during replacing event object"); + } +} + +JSValueRef JSCalendarEvent::getPropertyId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + CalendarEventPtr event = getPrivateObject(object); + + EventIdPtr eventId( new EventId() ); + eventId->setUId(event->getUId()); + eventId->setRecurrenceId(event->getRecurrenceId()); + eventId->setTimeZone(event->getTimeZone()); + return converter->toJSValueRef(eventId); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSCalendarEvent::getPropertyLastModifiedDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarEventPrivObject *privateObject = + static_cast(JSObjectGetPrivate(object)); + CalendarEventPtr event = privateObject->getObject(); + + if (!event) { + Throw(NullPointerException); + } + if (event->getLastModifiedDate() != 0) { + // Use the global context saved in the event struct. + return JSTZDate::createJSObject(privateObject->getContext(), event->getLastModifiedDate(), event->getTimeZone()); + } else { + return JSValueMakeUndefined(context); + } + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSCalendarEvent::getPropertyIsDetached(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + CalendarEventPtr event = getPrivateObject(object); + return converter.toJSValueRef(event->getIsDetached()); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarEvent::validate(JSContextRef ctx, + const JSObjectRef object, + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarEventPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (priv == NULL) { + return false; + } + CalendarEventPtr event = priv->getObject(); + if (!event) { + return false; + } + return event->validate(); +} + +} +} +} diff --git a/src/standards/Tizen/Calendar/JSCalendarEvent.h b/src/standards/Tizen/Calendar/JSCalendarEvent.h new file mode 100755 index 0000000..aba8a6e --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCalendarEvent.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _JS_CALENDAR_EVENT_H_ +#define _JS_CALENDAR_EVENT_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject CalendarEventPrivObject; + +class JSCalendarEvent +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static TizenApis::Api::Calendar::CalendarEventPtr getPrivateObject(JSObjectRef object); + + static void setPrivateObject(const TizenApis::Api::Calendar::CalendarEventPtr &event, + JSContextRef ctx, + const JSObjectRef object); + + static bool validate(JSContextRef ctx, + const JSObjectRef object, + JSValueRef* exception); + + private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Getters and setters for properties + */ + static JSValueRef getPropertyId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getPropertyLastModifiedDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getPropertyIsDetached(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); +}; + +} +} +} + +#endif /* _JS_CALENDAR_EVENT_H_ */ diff --git a/src/standards/Tizen/Calendar/JSCalendarItem.cpp b/src/standards/Tizen/Calendar/JSCalendarItem.cpp new file mode 100755 index 0000000..f01f38e --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCalendarItem.cpp @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include "JSCalendarItem.h" +#include "JSCalendarItemProperties.h" +#include "CalendarConverter.h" +#include "JSEventId.h" +#include +#include + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +#define TIZEN_CALENDAR_ITEM_ATTRIBUTENAME "CalendarItem" + +#define TIZEN_CALENDAR_ITEM_ID "id" +#define TIZEN_CALENDAR_ITEM_LASTMODIFIEDDATE "lastModificationDate" + +JSClassDefinition JSCalendarItem::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_CALENDAR_ITEM_ATTRIBUTENAME, + JSCalendarItemProperties::getClassRef(), + m_property, + NULL, // m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSCalendarItem::m_property[] = { + //EventProperties + { TIZEN_CALENDAR_ITEM_ID, getPropertyId, + NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_CALENDAR_ITEM_LASTMODIFIEDDATE, getPropertyLastModifiedDate, + NULL, kJSPropertyAttributeReadOnly }, + + { 0, 0, 0, 0 } +}; + +JSClassRef JSCalendarItem::m_jsClassRef = JSClassCreate(JSCalendarItem::getClassInfo()); + +void JSCalendarItem::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("entered"); + CalendarItemPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + CalendarEventPtr privateData(new CalendarEvent()); + priv = new CalendarItemPrivObject(context, privateData); + JSObjectSetPrivate(object, static_cast(priv)); + LogDebug("new event is created"); + } else { + LogDebug("private object already exists"); + } +} + +void JSCalendarItem::finalize(JSObjectRef object) +{ + LogDebug("entered"); +} + +const JSClassRef JSCalendarItem::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSCalendarItem::getClassInfo() +{ + return &m_classInfo; +} + +CalendarEventPtr JSCalendarItem::getPrivateObject(JSObjectRef object) +{ + LogDebug("entered"); + CalendarItemPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object is null"); + } + CalendarEventPtr result = priv->getObject(); + if (!result) { + ThrowMsg(NullPointerException, "Private object is null"); + } + return result; +} + +void JSCalendarItem::setPrivateObject(const CalendarEventPtr &event, + JSContextRef ctx, + const JSObjectRef object) +{ + LogDebug("entered"); + Try + { + CalendarItemPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + priv = new CalendarItemPrivObject(ctx, event); + if (!JSObjectSetPrivate(object, static_cast(priv))) { + delete priv; + } + } + Catch(Exception) + { + LogError("Error during replacing event object"); + } +} + +JSValueRef JSCalendarItem::getPropertyId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + CalendarEventPtr event = getPrivateObject(object); + + EventIdPtr eventId( new EventId() ); + eventId->setUId(event->getUId()); + LogDebug("event->getRecurrenceId() : " << event->getRecurrenceId()); + eventId->setRecurrenceId(event->getRecurrenceId()); + eventId->setTimeZone(event->getTimeZone()); + return converter->toJSValueRef(eventId); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSCalendarItem::getPropertyLastModifiedDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarItemPrivObject *privateObject = + static_cast(JSObjectGetPrivate(object)); + CalendarEventPtr item = privateObject->getObject(); + + if (!item) { + Throw(NullPointerException); + } + if (item->getLastModifiedDate() != 0) { + // Use the global context saved in the event struct. + return JSTZDate::createJSObject(privateObject->getContext(), item->getLastModifiedDate(), item->getTimeZone()); + } else { + return JSValueMakeUndefined(context); + } + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItem::validate(JSContextRef ctx, + const JSObjectRef object, + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarItemPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (priv == NULL) { + return false; + } + CalendarEventPtr event = priv->getObject(); + if (!event) { + return false; + } + return event->validate(); +} + +} +} +} diff --git a/src/standards/Tizen/Calendar/JSCalendarItem.h b/src/standards/Tizen/Calendar/JSCalendarItem.h new file mode 100755 index 0000000..c736778 --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCalendarItem.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _JS_CALENDAR_ITEM_H_ +#define _JS_CALENDAR_ITEM_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject CalendarItemPrivObject; + +class JSCalendarItem +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static TizenApis::Api::Calendar::CalendarEventPtr getPrivateObject(JSObjectRef object); + + static void setPrivateObject(const TizenApis::Api::Calendar::CalendarEventPtr &event, + JSContextRef ctx, + const JSObjectRef object); + + static bool validate(JSContextRef ctx, + const JSObjectRef object, + JSValueRef* exception); + + private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Getters and setters for properties + */ + static JSValueRef getPropertyId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getPropertyLastModifiedDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getPropertyIsDetached(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); +}; + +} +} +} + +#endif /* _JS_CALENDAR_ITEM_H_ */ diff --git a/src/standards/Tizen/Calendar/JSCalendarItemProperties.cpp b/src/standards/Tizen/Calendar/JSCalendarItemProperties.cpp new file mode 100755 index 0000000..963d669 --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCalendarItemProperties.cpp @@ -0,0 +1,1196 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "JSCalendarItemProperties.h" +#include "CalendarConverter.h" +#include "JSCategoryArray.h" +#include "JSEventId.h" +#include "JSEventAlarm.h" +#include "JSRecurrenceRule.h" +#include "JSAttendee.h" + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +#define TIZEN_CALENDAR_ITEM_PROPERTIES_ATTRIBUTENAME "CalendarItemProperties" + +#define TIZEN_CALENDAR_ITEM_DESCRIPTION "description" +#define TIZEN_CALENDAR_ITEM_SUMMARY "summary" +#define TIZEN_CALENDAR_ITEM_STARTTIME "startDate" +#define TIZEN_CALENDAR_ITEM_LOCATION "location" +#define TIZEN_CALENDAR_ITEM_LATITUDE "latitude" +#define TIZEN_CALENDAR_ITEM_LONGITUDE "longitude" +#define TIZEN_CALENDAR_ITEM_ORGANIZER "organizer" +#define TIZEN_CALENDAR_ITEM_VISIBILITY "visibility" +#define TIZEN_CALENDAR_ITEM_STATUS "status" +#define TIZEN_CALENDAR_ITEM_ALARMS "alarms" +#define TIZEN_CALENDAR_ITEM_CATEGORIES "categories" + +#define TIZEN_CALENDAR_EVENT_DURATION "duration" +#define TIZEN_CALENDAR_EVENT_IS_ALL_DAY "isAllDay" +#define TIZEN_CALENDAR_EVENT_ATTENDEES "attendees" +#define TIZEN_CALENDAR_EVENT_RECURRENCE_RULE "recurrenceRule" +#define TIZEN_CALENDAR_EVENT_AVAILABILITY "availability" + +#define TIZEN_CALENDAR_TASK_DUEDATE "dueDate" +#define TIZEN_CALENDAR_TASK_PRIORITY "priority" + +JSClassDefinition JSCalendarItemProperties::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_CALENDAR_ITEM_PROPERTIES_ATTRIBUTENAME, + 0, + m_property, + NULL, //m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSCalendarItemProperties::m_property[] = { + // Item Properties + { TIZEN_CALENDAR_ITEM_DESCRIPTION, getPropertyDescription, + setPropertyDescription, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_ITEM_SUMMARY, getPropertySummary, + setPropertySummary, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_ITEM_STARTTIME, getPropertyStartTime, + setPropertyStartTime, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_ITEM_LOCATION, getPropertyLocation, + setPropertyLocation, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_ITEM_LATITUDE, getPropertyLatitude, + setPropertyLatitude, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_ITEM_LONGITUDE, getPropertyLongitude, + setPropertyLongitude, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_ITEM_ORGANIZER, getPropertyOrganizer, + setPropertyOrganizer, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_ITEM_VISIBILITY, getPropertyVisibility, + setPropertyVisibility, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_ITEM_STATUS, getPropertyStatus, + setPropertyStatus, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_ITEM_ALARMS, getPropertyAlarms, + setPropertyAlarms, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_ITEM_CATEGORIES, getPropertyCategories, + setPropertyCategories, kJSPropertyAttributeNone }, + // Event Properties + { TIZEN_CALENDAR_EVENT_DURATION, getPropertyDuration, + setPropertyDuration, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_EVENT_IS_ALL_DAY, getPropertyIsAllDay, + setPropertyIsAllDay, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_EVENT_ATTENDEES, getPropertyAttendees, + setPropertyAttendees, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_EVENT_RECURRENCE_RULE, getPropertyRecurrenceRule, + setPropertyRecurrenceRule, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_EVENT_AVAILABILITY, getPropertyAvailability, + setPropertyAvailability, kJSPropertyAttributeNone }, + // Task Properties + { TIZEN_CALENDAR_TASK_DUEDATE, getPropertyDueDate, + setPropertyDueDate, kJSPropertyAttributeNone }, + { TIZEN_CALENDAR_TASK_PRIORITY, getPropertyPriority, + setPropertyPriority, kJSPropertyAttributeNone }, + + { 0, 0, 0, 0 } +}; + +JSClassRef JSCalendarItemProperties::m_jsClassRef = JSClassCreate(JSCalendarItemProperties::getClassInfo()); + +void JSCalendarItemProperties::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("entered"); + CalendarItemPropertiesPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + CalendarEventPtr privateData(new CalendarEvent()); + priv = new CalendarItemPropertiesPrivObject(context, privateData); + JSObjectSetPrivate(object, static_cast(priv)); + LogDebug("New CalendarItemPropertiesPrivObject is created."); + } else { + LogDebug("CalendarItemPropertiesPrivObject already exists."); + } +} + +void JSCalendarItemProperties::finalize(JSObjectRef object) +{ + LogDebug("entered"); + CalendarItemPropertiesPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; +} + +const JSClassRef JSCalendarItemProperties::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSCalendarItemProperties::getClassInfo() +{ + return &m_classInfo; +} + +CalendarEventPtr JSCalendarItemProperties::getPrivateObject(JSObjectRef object) +{ + LogDebug("entered"); + CalendarItemPropertiesPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object is null"); + } + CalendarEventPtr result = priv->getObject(); + if (!result) { + ThrowMsg(NullPointerException, "Private object is null"); + } + return result; +} + +void JSCalendarItemProperties::setPrivateObject(const CalendarEventPtr &event, + JSContextRef ctx, + const JSObjectRef object) +{ + LogDebug("entered"); + Try + { + CalendarItemPropertiesPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + priv = new CalendarItemPropertiesPrivObject(ctx, event); + if (!JSObjectSetPrivate(object, static_cast(priv))) { + delete priv; + } + } + Catch(Exception) + { + LogError("Error during replacing event object"); + } +} + +JSValueRef JSCalendarItemProperties::getPropertyDescription(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + CalendarEventPtr event = getPrivateObject(object); + return converter.toJSValueRef(event->getDescription()); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyDescription(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + CalendarEventPtr event = getPrivateObject(object); + std::string description = converter.toString(value); + event->setDescription(description); + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertySummary(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + CalendarEventPtr event = getPrivateObject(object); + return converter.toJSValueRef(event->getSubject()); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertySummary(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + CalendarEventPtr event = getPrivateObject(object); + std::string subject = converter.toString(value); + event->setSubject(subject); + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyStartTime(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarItemPropertiesPrivObject *privateObject = + static_cast(JSObjectGetPrivate(object)); + Converter converter(context); + CalendarEventPtr event = privateObject->getObject(); + + // Use the global context saved in the event struct. + return JSTZDate::createJSObject(privateObject->getContext(), event->getStartTime(), event->getTimeZone()); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyStartTime(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarEventPtr event = getPrivateObject(object); + TimeUtilConverter converter(context); + std::time_t startTime = converter.toTZDateTimeT(value); + std::time_t duration = 0; + duration = (event->getEndTime() - event->getStartTime()); + if (duration<0) + duration = 3600; // default 1 hour. + event->setEndTime(startTime + duration); + event->setStartTime(startTime); + + std::string timeZone = converter.getPropertiesInTZDate(value).timezone; + event->setTimeZone(timeZone); + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyLocation(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + CalendarEventPtr event = getPrivateObject(object); + return converter.toJSValueRef(event->getLocation()); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyLocation(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + CalendarEventPtr event = getPrivateObject(object); + std::string location = converter.toString(value); + event->setLocation(location); + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyCategories(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarEventPtr event = getPrivateObject(object); + CategoryListPtr categories = event->getCategories(); + if (categories) { + return JSCategoryArray::createArray(context, categories); + } + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyCategories(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarEventPtr event = getPrivateObject(object); + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + event->setCategories(converter->toCategories(value)); + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyStatus(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + CalendarEventPtr event = getPrivateObject(object); + std::string status = converter->toTizenValue(event->getStatus()); + return converter->toJSValueRef(status); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyStatus(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarEventPtr event(NULL); + Try + { + if (!JSValueIsNumber(context, value)) { + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; + } + event = getPrivateObject(object); + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + CalendarEvent::EventStatus status = + converter->toEventStatus(converter->toString(value)); + event->setStatus(status); + return true; + } + Catch(ConversionException) + { + LogWarning("trying to set incorrect value"); + event->setStatus(CalendarEvent::INVALID_STATUS); + return true; + } + Catch(InvalidArgumentException) + { + LogWarning("trying to set incorrect value"); + event->setStatus(CalendarEvent::INVALID_STATUS); + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyAlarms(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + CalendarEventPtr event = getPrivateObject(object); + + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + if (NULL == jsResult) { + ThrowMsg(NullPointerException, "Could not create js array object"); + } + for( unsigned int i=0; igetAlarmsTick().size(); i++) { + EventAlarmPtr alarm(new EventAlarm()); + alarm->setMinutes( event->getAlarmsTick().at(i) ); // Default unit is minute. + alarm->setDays(0); + std::vector methodVector; + methodVector.push_back(event->getAlarmsType().at(i)); // Only one alarm type is saved. + alarm->setMethods(methodVector); + alarm->setTimeZone(event->getTimeZone()); + + if (!JSSetArrayElement(context, jsResult, i, JSEventAlarm::createJSObject(context, alarm))) { + ThrowMsg(UnknownException, "Could not insert value into js array"); + } + } + return jsResult; + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyAlarms(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarEventPtr event(NULL); + Try + { + event = getPrivateObject(object); + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + + EventAlarmListPtr alarms = converter->toVectorOfEventAlarms(value); + std::vector alarmsType; + std::vector alarmsTick; + // Set the multiple alarms. + for( unsigned int i=0; isize(); i++) { + EventAlarmPtr theAlarm = alarms->at(i); + alarmsType.push_back(converter->toEventAlarmType(theAlarm->getMethods().at(0))); + if( 0 < theAlarm->getAbsoluteDate() ) { + alarmsTick.push_back(theAlarm->getAbsoluteDate()/60); // + } else { + alarmsTick.push_back(theAlarm->getMinutes() + theAlarm->getDays()*24*60); + } + } + event->setAlarmsType(alarmsType); + event->setAlarmsTick(alarmsTick); + return true; + } + Catch(ConversionException) + { + LogWarning("trying to set incorrect value"); + return true; + } + Catch(InvalidArgumentException) + { + LogWarning("trying to set incorrect value"); + return true; + } + Catch(Exception) + { + LogError("Error during setting a value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyOrganizer(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + CalendarEventPtr event = getPrivateObject(object); + return converter.toJSValueRef(event->getOrganizer()); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyOrganizer(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + CalendarEventPtr event = getPrivateObject(object); + std::string organizer = converter.toString(value); + event->setOrganizer(organizer); + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyVisibility(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + CalendarEventPtr event = getPrivateObject(object); + std::string visibility = converter->toTizenValue(event->getVisibility()); + return converter->toJSValueRef(visibility); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyVisibility(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarEventPtr event(NULL); + Try + { + if (!JSValueIsNumber(context, value)) { + Throw(InvalidArgumentException); + return false; + } + event = getPrivateObject(object); + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + CalendarEvent::EventVisibility visibility = + converter->toEventVisibility(converter->toString(value)); + event->setVisibility(visibility); + return true; + } + Catch(ConversionException) + { + LogWarning("trying to set incorrect value"); + event->setVisibility(CalendarEvent::INVALID_VISIBILITY); + return true; + } + Catch(InvalidArgumentException) + { + LogWarning("trying to set incorrect value"); + event->setVisibility(CalendarEvent::INVALID_VISIBILITY); + return true; + } + Catch(Exception) + { + LogError("Error during setting a value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyLatitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + CalendarEventPtr event = getPrivateObject(object); + double latitude = event->getLatitude(); + return converter.toJSValueRef(latitude); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); + +} + +bool JSCalendarItemProperties::setPropertyLatitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + CalendarEventPtr event = getPrivateObject(object); + double latitude = converter.toDouble(value); + event->setLatitude(latitude); + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyLongitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + CalendarEventPtr event = getPrivateObject(object); + double longitude = event->getLongitude(); + return converter.toJSValueRef(longitude); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); + +} + +bool JSCalendarItemProperties::setPropertyLongitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + CalendarEventPtr event = getPrivateObject(object); + double longitude = converter.toDouble(value); + event->setLongitude(longitude); + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +// event properties +JSValueRef JSCalendarItemProperties::getPropertyDuration(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarEventPtr event = getPrivateObject(object); + CalendarItemPropertiesPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + + // Use the global context saved in the event struct. + TimeUtilConverter converter(priv->getContext()); + long length = event->getEndTime() - event->getStartTime(); // in seconds only + LogDebug("event->getStartTime():"<< event->getStartTime() << ", length:" << length); + JSValueRef temp = converter.makeMillisecondDurationObject( length*1000 ); + LogDebug("1"); + LogDebug("temp : " << temp); + return converter.makeMillisecondDurationObject( length*1000 ); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyDuration(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarEventPtr event = getPrivateObject(object); + TimeUtilConverter converter(context); + long length = converter.getDurationLength(value, exception); + int unit = converter.getDurationUnit(value, exception); + if (length < 0) { + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + return false; + } + if( SECONDS_UNIT==unit ) { + event->setEndTime(event->getStartTime() + length); + } else if ( MINUTES_UNIT==unit ) { + event->setEndTime(event->getStartTime() + length*60); + } else if ( HOURS_UNIT==unit ) { + event->setEndTime(event->getStartTime() + length*60*60); + } else if ( DAYS_UNIT==unit ) { + event->setEndTime(event->getStartTime() + length*24*60*60); + } else if ( MSECS_UNIT==unit ) { + event->setEndTime(event->getStartTime() + length/1000); + } else { + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + return false; + } + + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyRecurrenceRule(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + CalendarEventPtr event = getPrivateObject(object); + EventRecurrenceRulePtr rrule = event->getRecurrenceRule(); + + if (rrule) { + return JSRecurrenceRule::createJSRecurrenceRule(context, rrule); + } + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyRecurrenceRule(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarEventPtr event(NULL); + Try + { + event = getPrivateObject(object); + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + event->setRecurrenceRule(converter->toEventRecurrenceRule(value)); + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyIsAllDay(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + CalendarEventPtr event = getPrivateObject(object); + return converter->toJSValueRef(event->getIsAllDay()); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyIsAllDay(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + CalendarEventPtr event = getPrivateObject(object); + Converter converter(context); + event->setIsAllDay(converter.toBool(value)); + return true; + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyAvailability(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + CalendarEventPtr event = getPrivateObject(object); + std::string availability = converter->toTizenValue(event->getAvailability()); + return converter->toJSValueRef(availability); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyAvailability(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarEventPtr event(NULL); + Try + { + if (!JSValueIsNumber(context, value)) { + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; + } + event = getPrivateObject(object); + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + CalendarEvent::EventAvailability availability = + converter->toEventAvailability(converter->toString(value)); + event->setAvailability(availability); + return true; + } + Catch(ConversionException) + { + LogWarning("trying to set incorrect value"); + event->setAvailability(CalendarEvent::INVALID_AVAILABILITY); + return true; + } + Catch(InvalidArgumentException) + { + LogWarning("trying to set incorrect value"); + event->setAvailability(CalendarEvent::INVALID_AVAILABILITY); + return true; + } + Catch(Exception) + { + LogError("Error during setting a value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyAttendees(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarEventPtr event = getPrivateObject(object); + EventAttendeeListPtr attendees = event->getAttendees(); + if (attendees) { + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + if (NULL == jsResult) { + ThrowMsg(NullPointerException, "Could not create js array object"); + } + for(unsigned int i=0; isize(); i++) { + if (!JSSetArrayElement(context, jsResult, i, JSAttendee::createJSAttendee(context, attendees->at(i)))) { + ThrowMsg(UnknownException, "Could not insert value into js array"); + } + } + return jsResult; + } + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyAttendees(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarEventPtr event = getPrivateObject(object); + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + event->setAttendees(converter->toVectorOfAttendees(value)); + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +// task properties +JSValueRef JSCalendarItemProperties::getPropertyDueDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarItemPropertiesPrivObject *privateObject = + static_cast(JSObjectGetPrivate(object)); + CalendarEventPtr task = privateObject->getObject(); + if(CalendarEvent::TASK_TYPE != task->getCalendarType()) { + return JSValueMakeUndefined(context); + } + + if (!task) { + Throw(NullPointerException); + } + if (task->getEndTime() != 0) { + // Use the global context saved in the event struct. + return JSTZDate::createJSObject(privateObject->getContext(), task->getEndTime(), task->getTimeZone()); + } else { + return JSValueMakeUndefined(context); + } + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyDueDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarEventPtr task = getPrivateObject(object); + Try + { + if (!task) { + Throw(NullPointerException); + } + + TimeUtilConverter converter(context); + std::time_t dueDate = converter.toTZDateTimeT(value); + + task->setEndTime(dueDate); + + if( task->getTimeZone().empty() ) { + std::string timeZone = converter.getPropertiesInTZDate(value).timezone; + task->setTimeZone(timeZone); + } + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + if (task) { + task->setEndTime(0); + } + } + return false; +} + +JSValueRef JSCalendarItemProperties::getPropertyPriority(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + CalendarEventPtr task = getPrivateObject(object); + if (!task) { + Throw(NullPointerException); + } + if(CalendarEvent::LOW_PRIORITY <= task->getPriority() || + CalendarEvent::HIGH_PRIORITY >= task->getPriority()) { + return JSValueMakeUndefined(context); + } + + std::string priority = converter->toTizenValue(task->getPriority()); + return converter->toJSValueRef(priority); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarItemProperties::setPropertyPriority(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarEventPtr task = getPrivateObject(object); + Try + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + if (!task) { + Throw(NullPointerException); + } + CalendarEvent::TaskPriority priority = + converter->toTaskPriority(converter->toString(value)); + task->setPriority(priority); + return true; + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + if (task) { + task->setPriority(CalendarEvent::INVALID_PRIORITY); + } + } + return false; +} + +bool JSCalendarItemProperties::validate(JSContextRef ctx, + const JSObjectRef object, + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarItemPropertiesPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (priv == NULL) { + return false; + } + CalendarEventPtr event = priv->getObject(); + if (!event) { + return false; + } + return event->validate(); +} + +} +} +} diff --git a/src/standards/Tizen/Calendar/JSCalendarItemProperties.h b/src/standards/Tizen/Calendar/JSCalendarItemProperties.h new file mode 100755 index 0000000..944d04d --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCalendarItemProperties.h @@ -0,0 +1,256 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _JS_CALENDAR_ITEM_PROPERTIES_H_ +#define _JS_CALENDAR_ITEM_PROPERTIES_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject CalendarItemPropertiesPrivObject; + +class JSCalendarItemProperties +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static TizenApis::Api::Calendar::CalendarEventPtr getPrivateObject(JSObjectRef object); + + static void setPrivateObject(const TizenApis::Api::Calendar::CalendarEventPtr &event, + JSContextRef ctx, + const JSObjectRef object); + + static bool validate(JSContextRef ctx, + const JSObjectRef object, + JSValueRef* exception); + + private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Getters and setters for properties + */ + static JSValueRef getPropertyDescription(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyDescription(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertySummary(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertySummary(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyStartTime(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyStartTime(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyLocation(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyLocation(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyLatitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyLatitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyLongitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyLongitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyOrganizer(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyOrganizer(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyVisibility(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyVisibility(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyStatus(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyStatus(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyAlarms(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyAlarms(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyCategories(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyCategories(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + // event properties + static JSValueRef getPropertyIsAllDay(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyIsAllDay(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyDuration(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyDuration(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyAttendees(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyAttendees(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyAvailability(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyAvailability(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyRecurrenceRule(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyRecurrenceRule(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + // Task properties + static JSValueRef getPropertyDueDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyDueDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static JSValueRef getPropertyPriority(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static bool setPropertyPriority(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; + +} +} +} + +#endif + diff --git a/src/standards/Tizen/Calendar/JSCalendarManager.cpp b/src/standards/Tizen/Calendar/JSCalendarManager.cpp new file mode 100755 index 0000000..2333469 --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCalendarManager.cpp @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "JSCalendarItem.h" +#include "JSCalendarManager.h" +#include "JSCalendar.h" +#include "CalendarConverter.h" +#include "CalendarResponseDispatcher.h" +#include "plugin_config.h" + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Commons; + +#define TIZEN_CALENDAR_MANAGER_FUNCTION_GET_CALENDARS "getCalendars" +#define TIZEN_CALENDAR_MANAGER_FUNCTION_GET_DEFAULT_CALENDAR "getDefaultCalendar" +#define TIZEN_CALENDAR_MANAGER_ATTRIBUTENAME "calendar" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +JSClassDefinition JSCalendarManager::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_CALENDAR_MANAGER_ATTRIBUTENAME, + 0, + NULL, + m_function, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticFunction JSCalendarManager::m_function[] = { + { TIZEN_CALENDAR_MANAGER_FUNCTION_GET_CALENDARS, + getCalendars, kJSPropertyAttributeNone }, + + { TIZEN_CALENDAR_MANAGER_FUNCTION_GET_DEFAULT_CALENDAR, + getDefaultCalendar, kJSPropertyAttributeNone }, + + { 0, 0, 0 } +}; + +JSClassRef JSCalendarManager::m_jsClassRef = JSClassCreate( + JSCalendarManager::getClassInfo()); + +void JSCalendarManager::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("entered"); + CalendarManagerPrivObject *privateObject = + static_cast(JSObjectGetPrivate(object)); + if (NULL == privateObject) { + ICalendarManagerPtr calendarManager = + Api::Calendar::CalendarFactory::getInstance().createCalendarManagerObject(); + privateObject = new CalendarManagerPrivObject(context, calendarManager); + if (!JSObjectSetPrivate(object, static_cast(privateObject))) { + delete privateObject; + } + } +} + +void JSCalendarManager::finalize(JSObjectRef object) +{ + LogDebug("entered"); + CalendarManagerPrivObject *privateObject = + static_cast(JSObjectGetPrivate(object)); + delete privateObject; +} + +JSValueRef JSCalendarManager::getCalendars(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + CalendarManagerPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + JSContextRef globalContext = privateObject->getContext(); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(globalContext, CALENDAR_FUNCTION_API_GET_CALENDARS); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount < 2) { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext); + cbm->setObject(thisObject); + + CalendarConverter converter(context); + + Try { + if (argumentCount > 2) { + cbm->setOnError(converter.toFunctionOrNull(arguments[2])); + } + cbm->setOnSuccess(converter.toFunction(arguments[1])); + + CalendarEvent::CalendarType calendarType = CalendarEvent::EVENT_TYPE; + if (!JSValueIsString(context, arguments[0])) { + LogError("Invalid type of type parameter."); + Throw(InvalidArgumentException); + } else { + calendarType = converter.toCalendarType(converter.toString(arguments[0])); + } + + IEventGetCalendarsPtr dplEvent(new IEventGetCalendars()); + dplEvent->setType(calendarType); + dplEvent->setPrivateData(DPL::StaticPointerCast(cbm)); + dplEvent->setForAsynchronousCall(&CalendarResponseDispatcher::getInstance()); + privateObject->getObject()->getCalendars(dplEvent); + + } + Catch(InvalidArgumentException) { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(ConversionException) { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSCalendarManager::getDefaultCalendar(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + CalendarManagerPrivObject *privateObject = + static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + + JSContextRef globalContext = privateObject->getContext(); + + AceSecurityStatus status = CALENDAR_CHECK_ACCESS(globalContext, CALENDAR_FUNCTION_API_GET_DEFAULT_CALENDAR); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount == 0) { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + + Try { + CalendarConverter converter(context); + CalendarEvent::CalendarType calendarType = CalendarEvent::EVENT_TYPE; + if (!JSValueIsString(context, arguments[0])) { + LogError("Invalid type of type parameter."); + Throw(InvalidArgumentException); + } else { + calendarType = converter.toCalendarType(converter.toString(arguments[0])); + } + + IEventGetDefaultCalendarPtr dplEvent(new IEventGetDefaultCalendar()); + dplEvent->setForSynchronousCall(); + dplEvent->setType(calendarType); + privateObject->getObject()->getDefaultCalendar(dplEvent); + + if (dplEvent->getResult()) { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(globalContext); // should be global! + return converter->toJSValueRefCalendar(dplEvent->getCalendar()); + } else { + Throw(UnknownException); + } + } + Catch(ConversionException) { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + Catch(InvalidArgumentException) { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR); + } + Catch(Exception) { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::UNKNOWN_ERROR); + } + return JSValueMakeNull(context); +} + +const JSClassRef JSCalendarManager::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSCalendarManager::getClassInfo() +{ + return &m_classInfo; +} + +} +} +} diff --git a/src/standards/Tizen/Calendar/JSCalendarManager.h b/src/standards/Tizen/Calendar/JSCalendarManager.h new file mode 100755 index 0000000..8fb639a --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCalendarManager.h @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _JS_TIZEN_CALENDAR_MANAGER_H_ +#define _JS_TIZEN_CALENDAR_MANAGER_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject CalendarManagerPrivObject; + +#define TIZEN_CALENDAR_PROPERTY_VCALENDAR_20_FORMAT "ICALENDAR_20" +#define TIZEN_CALENDAR_PROPERTY_VCALENDAR_10_FORMAT "VCALENDAR_10" + +#define TIZEN_CALENDAR_PROPERTY_TENTATIVE_STATUS "TENTATIVE" +#define TIZEN_CALENDAR_PROPERTY_CONFIRMED_STATUS "CONFIRMED" +#define TIZEN_CALENDAR_PROPERTY_CANCELLED_STATUS "CANCELLED" +#define TIZEN_CALENDAR_PROPERTY_NEEDS_ACTION_STATUS "NEEDS_ACTION" +#define TIZEN_CALENDAR_PROPERTY_IN_PROCESS_STATUS "IN_PROCESS" +#define TIZEN_CALENDAR_PROPERTY_COMPLETED_STATUS "COMPLETED" + +#define TIZEN_CALENDAR_PROPERTY_HIGH_PRIORITY "HIGH" +#define TIZEN_CALENDAR_PROPERTY_MEDIUM_PRIORITY "MEDIUM" +#define TIZEN_CALENDAR_PROPERTY_LOW_PRIORITY "LOW" + +#define TIZEN_CALENDAR_PROPERTY_PUBLIC_VISIBILITY "PUBLIC" +#define TIZEN_CALENDAR_PROPERTY_PRIVATE_VISIBILITY "PRIVATE" +#define TIZEN_CALENDAR_PROPERTY_CONFIDENTIAL_VISIBILITY "CONFIDENTIAL" + +#define TIZEN_CALENDAR_PROPERTY_BUSY "BUSY" +#define TIZEN_CALENDAR_PROPERTY_BUSY_UNAVAILABLE_FB "BUSY_UNAVAILABLE" +#define TIZEN_CALENDAR_PROPERTY_FREE "FREE" +#define TIZEN_CALENDAR_PROPERTY_BUSY_TENTATIVE "BUSY_TENTATIVE" + +#define TIZEN_CALENDAR_PROPERTY_REQ_PARTICIPANT_ROLE "REQ_PARTICIPANT" +#define TIZEN_CALENDAR_PROPERTY_OPT_PARTICIPANT_ROLE "OPT_PARTICIPANT" +#define TIZEN_CALENDAR_PROPERTY_NON_PARTICIPANT_ROLE "NON_PARTICIPANT" +#define TIZEN_CALENDAR_PROPERTY_CHAIR_ROLE "CHAIR" + +#define TIZEN_CALENDAR_PROPERTY_PENDING_STATUS "PENDING" +#define TIZEN_CALENDAR_PROPERTY_ACCEPTED_STATUS "ACCEPTED" +#define TIZEN_CALENDAR_PROPERTY_DECLINED_STATUS "DECLINED" +#define TIZEN_CALENDAR_PROPERTY_TENTATIVE_STATUS "TENTATIVE" +#define TIZEN_CALENDAR_PROPERTY_DELEGATED_STATUS "DELEGATED" +#define TIZEN_CALENDAR_PROPERTY_COMPLETED_STATUS "COMPLETED" +#define TIZEN_CALENDAR_PROPERTY_IN_PROCESS_STATUS "IN_PROCESS" + +#define TIZEN_CALENDAR_PROPERTY_INDIVIDUAL_TYPE "INDIVIDUAL" +#define TIZEN_CALENDAR_PROPERTY_GROUP_TYPE "GROUP" +#define TIZEN_CALENDAR_PROPERTY_RESOURCE_TYPE "RESOURCE" +#define TIZEN_CALENDAR_PROPERTY_ROOM_TYPE "ROOM" +#define TIZEN_CALENDAR_PROPERTY_UNKNOWN_TYPE "UNKNOWN" + +#define TIZEN_CALENDAR_PROPERTY_NO_RECURRENCE "NO_RECURRENCE" +#define TIZEN_CALENDAR_PROPERTY_DAILY_RECURRENCE "DAILY" +#define TIZEN_CALENDAR_PROPERTY_WEEKLY_RECURRENCE "WEEKLY" +#define TIZEN_CALENDAR_PROPERTY_MONTHLY_RECURRENCE "MONTHLY" +#define TIZEN_CALENDAR_PROPERTY_YEARLY_RECURRENCE "YEARLY" + +#define TIZEN_CALENDAR_PROPERTY_NO_ALARM "NO_ALARM" +#define TIZEN_CALENDAR_PROPERTY_SILENT_ALARM "SILENT" +#define TIZEN_CALENDAR_PROPERTY_SOUND_ALARM "SOUND" + +#define TIZEN_CALENDAR_PROPERTY_TYPE_EVENT "EVENT" +#define TIZEN_CALENDAR_PROPERTY_TYPE_TASK "TASK" + +class JSCalendarManager +{ + public: + enum TizenAlarmType + { + NO_ALARM = 0, + SILENT_ALARM = 1, + SOUND_ALARM = 2, + INVALID_ALARM = 10000 + }; + + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + private: + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to + * the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + /** + * This structure contains properties and callbacks + * that define a type of object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Get Calendars. + */ + static JSValueRef getCalendars(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Get a default calendar. + */ + static JSValueRef getDefaultCalendar(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +} +} +} +#endif /* _JS_TIZEN_CALENDAR_MANAGER_H_ */ diff --git a/src/standards/Tizen/Calendar/JSCalendarTask.cpp b/src/standards/Tizen/Calendar/JSCalendarTask.cpp new file mode 100755 index 0000000..5564a63 --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCalendarTask.cpp @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include "JSCalendarTask.h" +#include "JSCalendarItemProperties.h" +#include "CalendarConverter.h" +#include "JSEventId.h" +#include +#include + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +#define TIZEN_CALENDAR_TASK_ATTRIBUTENAME "CalendarTask" + +#define TIZEN_CALENDAR_TASK_ID "id" +#define TIZEN_CALENDAR_TASK_LASTMODIFIEDDATE "lastModificationDate" + + +JSClassDefinition JSCalendarTask::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_CALENDAR_TASK_ATTRIBUTENAME, + JSCalendarItemProperties::getClassRef(), + m_property, + NULL, // m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSCalendarTask::m_property[] = { + //EventProperties + { TIZEN_CALENDAR_TASK_ID, getPropertyId, + NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_CALENDAR_TASK_LASTMODIFIEDDATE, getPropertyLastModifiedDate, + NULL, kJSPropertyAttributeReadOnly }, + + { 0, 0, 0, 0 } +}; + +JSClassRef JSCalendarTask::m_jsClassRef = JSClassCreate(JSCalendarTask::getClassInfo()); + +void JSCalendarTask::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("entered"); + CalendarTaskPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + CalendarEventPtr privateData(new CalendarEvent()); + priv = new CalendarTaskPrivObject(context, privateData); + JSObjectSetPrivate(object, static_cast(priv)); + LogDebug("new event is created"); + } else { + LogDebug("private object already exists"); + } +} + +void JSCalendarTask::finalize(JSObjectRef object) +{ + LogDebug("entered"); +} + +const JSClassRef JSCalendarTask::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSCalendarTask::getClassInfo() +{ + return &m_classInfo; +} + +CalendarEventPtr JSCalendarTask::getPrivateObject(JSObjectRef object) +{ + LogDebug("entered"); + CalendarTaskPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object is null"); + } + CalendarEventPtr result = priv->getObject(); + if (!result) { + ThrowMsg(NullPointerException, "Private object is null"); + } + return result; +} + +void JSCalendarTask::setPrivateObject(const CalendarEventPtr &event, + JSContextRef ctx, + const JSObjectRef object) +{ + LogDebug("entered"); + Try + { + CalendarTaskPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + priv = new CalendarTaskPrivObject(ctx, event); + if (!JSObjectSetPrivate(object, static_cast(priv))) { + delete priv; + } + } + Catch(Exception) + { + LogError("Error during replacing event object"); + } +} + +JSValueRef JSCalendarTask::getPropertyId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + CalendarEventPtr event = getPrivateObject(object); + + EventIdPtr eventId( new EventId() ); + eventId->setUId(event->getUId()); + eventId->setRecurrenceId(event->getRecurrenceId()); + eventId->setTimeZone(event->getTimeZone()); + return converter->toJSValueRef(eventId); + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSCalendarTask::getPropertyLastModifiedDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + CalendarTaskPrivObject *privateObject = + static_cast(JSObjectGetPrivate(object)); + CalendarEventPtr task = privateObject->getObject(); + + if (!task) { + Throw(NullPointerException); + } + if (task->getLastModifiedDate() != 0) { + // Use the global context saved in the event struct. + return JSTZDate::createJSObject(privateObject->getContext(), task->getLastModifiedDate(), task->getTimeZone()); + } else { + return JSValueMakeUndefined(context); + } + } + Catch(Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCalendarTask::validate(JSContextRef ctx, + const JSObjectRef object, + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarTaskPrivObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (priv == NULL) { + return false; + } + CalendarEventPtr event = priv->getObject(); + if (!event) { + return false; + } + return event->validate(); +} + +} +} +} diff --git a/src/standards/Tizen/Calendar/JSCalendarTask.h b/src/standards/Tizen/Calendar/JSCalendarTask.h new file mode 100755 index 0000000..8ac4d36 --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCalendarTask.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _JS_CALENDAR_TASK_H_ +#define _JS_CALENDAR_TASK_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject CalendarTaskPrivObject; + +class JSCalendarTask +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static TizenApis::Api::Calendar::CalendarEventPtr getPrivateObject(JSObjectRef object); + + static void setPrivateObject(const TizenApis::Api::Calendar::CalendarEventPtr &event, + JSContextRef ctx, + const JSObjectRef object); + + static bool validate(JSContextRef ctx, + const JSObjectRef object, + JSValueRef* exception); + + private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Getters and setters for properties + */ + static JSValueRef getPropertyId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getPropertyLastModifiedDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); +}; + +} +} +} + +#endif /* _JS_CALENDAR_TASK_H_ */ diff --git a/src/standards/Tizen/Calendar/JSCategoryArray.cpp b/src/standards/Tizen/Calendar/JSCategoryArray.cpp new file mode 100755 index 0000000..8b56f09 --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCategoryArray.cpp @@ -0,0 +1,566 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "JSCategoryArray.h" +#include +#include +#include +#include +#include + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +JSClassDefinition JSCategoryArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSCategoryArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSCategoryArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSCategoryArray::m_jsClassRef = JSClassCreate( + JSCategoryArray::getClassInfo()); + +JSValueRef JSCategoryArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + Try + { + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + CategoryListPtr categories = priv->getObject(); + if (categories) { + Converter converter(context); + return converter.toJSValueRef(categories->size()); + } + } + Catch(Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +CategoryListPtr JSCategoryArray::getCategories(JSContextRef context, + JSObjectRef object) +{ + LogDebug("enter"); + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + return priv->getObject(); +} + +JSObjectRef JSCategoryArray::createArray(JSContextRef context, + const CategoryListPtr &categories) +{ + JSCategoryArrayPrivate *priv = new JSCategoryArrayPrivate(context, + categories); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSCategoryArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSCategoryArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +void JSCategoryArray::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("enter"); +} + +void JSCategoryArray::finalize(JSObjectRef object) +{ + LogDebug("enter"); + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSCategoryArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + LogDebug("enter"); + Converter converter(context); + Try + { + size_t index = converter.toSizeT(propertyName); + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + CategoryListPtr categories = priv->getObject(); + if (index < categories->size()) { + return true; + } + } + Catch(Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSCategoryArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + Converter converter(context); + Try + { + size_t index = converter.toSizeT(propertyName); + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + CategoryListPtr categories = priv->getObject(); + if (index < categories->size()) { + std::string result = categories->at(index); + if (!result.empty()) { + return converter.toJSValueRef(result); + } + } + } + Catch(Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSCategoryArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("enter"); + Converter converter(context); + Try + { + size_t index = converter.toSizeT(propertyName); + std::string category; + if (!JSValueIsUndefined(context, value)) { + category = converter.toString(value); + } + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + CategoryListPtr categories = priv->getObject(); + if (!categories) { + Throw(NullPointerException); + } + if (categories->size() <= index) { + categories->resize(index + 1); + } + (*categories)[index] = category; + return true; + } + Catch(Exception) + { + LogError("error occured"); + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + } + return false; +} + +JSValueRef JSCategoryArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("enter"); + Try + { + CategoryListPtr categories = CategoryListPtr(new CategoryList()); + JSCategoryArrayPrivate *newPrivateObject = new JSCategoryArrayPrivate( + context, + categories); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current categories + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(thisObject)); + CategoryListPtr currentCategories = priv->getObject(); + for (size_t i = 0; i < currentCategories->size(); ++i) { + categories->push_back(currentCategories->at(i)); + } + + //copy submitted arrays + Converter converter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter.toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + categories->push_back(converter.toString(att)); + } + } + return result; + } + Catch(Exception) + { + LogError("error occured"); + } + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); +} + +JSValueRef JSCategoryArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + Converter converter(context); + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(thisObject)); + CategoryListPtr currentCategories = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter.toString(arguments[0]); + } + for (size_t i = 0; i < currentCategories->size(); ++i) { + if (i != 0) { + result += separator; + } + result += currentCategories->at(i); + } + return converter.toJSValueRef(result); + } + Catch(Exception) + { + LogError("error occured"); + } + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); +} + +JSValueRef JSCategoryArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(thisObject)); + CategoryListPtr currentCategories = priv->getObject(); + if (currentCategories->size() > 0) { + std::string result = currentCategories->at( + currentCategories->size() - 1); + currentCategories->pop_back(); + return converter.toJSValueRef(result); + } + } + Catch(Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSCategoryArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(thisObject)); + CategoryListPtr currentCategories = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentCategories->push_back(converter.toString(arguments[i])); + } + return converter.toJSValueRef(currentCategories->size()); + } + Catch(Exception) + { + LogError("error occured"); + } + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); +} + +JSValueRef JSCategoryArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(thisObject)); + CategoryListPtr currentCategories = priv->getObject(); + std::reverse(currentCategories->begin(), currentCategories->end()); + return thisObject; + } + Catch(Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSCategoryArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(thisObject)); + CategoryListPtr currentCategories = priv->getObject(); + if (currentCategories->size() > 0) { + std::string result = currentCategories->at(0); + currentCategories->erase(currentCategories->begin()); + return converter.toJSValueRef(result); + } + } + Catch(Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSCategoryArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + Converter converter(context); + CategoryListPtr categories = CategoryListPtr(new CategoryList()); + JSCategoryArrayPrivate *newPrivateObject = new JSCategoryArrayPrivate( + context, + categories); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current categories + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(thisObject)); + CategoryListPtr currentCategories = priv->getObject(); + std::size_t first = converter.toSizeT(arguments[0]); + std::size_t last = currentCategories->size() - 1; + if (argumentCount > 1) { + last = converter.toSizeT(arguments[1]); + if (last >= currentCategories->size()) { + last = currentCategories->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + categories->push_back(currentCategories->at(i)); + } + + return result; + } + Catch(Exception) + { + LogError("error occured"); + } + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); +} + +JSValueRef JSCategoryArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + Converter converter(context); + JSCategoryArrayPrivate* priv = + static_cast(JSObjectGetPrivate(thisObject)); + CategoryListPtr currentCategories = priv->getObject(); + std::sort(currentCategories->begin(), currentCategories->end()); + return thisObject; + } + Catch(Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSCategoryArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSCategoryArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSCategoryArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSCategoryArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} +} +} diff --git a/src/standards/Tizen/Calendar/JSCategoryArray.h b/src/standards/Tizen/Calendar/JSCategoryArray.h new file mode 100755 index 0000000..84b9432 --- /dev/null +++ b/src/standards/Tizen/Calendar/JSCategoryArray.h @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _JS_CATEGORY_ARRAY_H_ +#define _JS_CATEGORY_ARRAY_H_ + +#include +#include +#include +#include +#include + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +typedef PrivateObjectT::Type +JSCategoryArrayPrivate; + +class JSCategoryArray +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const Api::Calendar::CategoryListPtr &categories); + + static Api::Calendar::CategoryListPtr getCategories(JSContextRef context, + JSObjectRef object); + + private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} +} +} + +#endif /* _JS_ARRAY_H_ */ diff --git a/src/standards/Tizen/Calendar/JSEventAlarm.cpp b/src/standards/Tizen/Calendar/JSEventAlarm.cpp new file mode 100755 index 0000000..fee4c81 --- /dev/null +++ b/src/standards/Tizen/Calendar/JSEventAlarm.cpp @@ -0,0 +1,214 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "JSEventAlarm.h" +#include +#include +#include +#include +#include +#include + +using namespace TizenApis::Api::Calendar; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +#define TIZEN_ALARM_ATTRIBUTENAME "Alarm" +#define TIZEN_ABSOLUTE_DATE "absoluteDate" +#define TIZEN_MINUTES "minutes" +#define TIZEN_DAYS "days" +#define TIZEN_METHODS "methods" + +JSClassDefinition JSEventAlarm::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_ALARM_ATTRIBUTENAME, + 0, + m_property, + NULL, //m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSEventAlarm::m_property[] = { + { TIZEN_ABSOLUTE_DATE, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_MINUTES, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_DAYS, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_METHODS, getProperty, setProperty, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSEventAlarm::m_jsClassRef = JSClassCreate( + JSEventAlarm::getClassInfo()); + +const JSClassDefinition* JSEventAlarm::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSEventAlarm::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +JSObjectRef JSEventAlarm::createJSObject(JSContextRef context, EventAlarmPtr alarm) +{ + EventAlarmPrivateObject *priv = new EventAlarmPrivateObject(context, alarm); + return JSObjectMake(context, getClassRef(), priv); +} + +EventAlarmPtr JSEventAlarm::getAlarm(JSObjectRef object) +{ + LogDebug("entered"); + EventAlarmPrivateObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + EventAlarmPtr result = priv->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + return result; +} + +void JSEventAlarm::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("enter"); +} + +void JSEventAlarm::finalize(JSObjectRef object) +{ + LogDebug("enter"); + EventAlarmPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +JSValueRef JSEventAlarm::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Try + { + EventAlarmPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + EventAlarmPtr alarm = priv->getObject(); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ABSOLUTE_DATE)) { + if (!alarm) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (alarm->getAbsoluteDate() != 0) { + // Use the global context saved in the event struct. + return JSTZDate::createJSObject(priv->getContext(), alarm->getAbsoluteDate(), alarm->getTimeZone()); + } else { + return JSValueMakeUndefined(context); + } + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_MINUTES)) { + return converter.toJSValueRef(alarm->getMinutes()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_DAYS)) { + return converter.toJSValueRef(alarm->getDays()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_METHODS)) { + std::vector result; + std::vector methods = alarm->getMethods(); + for(std::vector::iterator i = methods.begin(); i != methods.end(); i++) + result.push_back(converter.toJSValueRef(*i)); + return converter.toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSEventAlarm::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Try + { + EventAlarmPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + EventAlarmPtr alarm = priv->getObject(); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ABSOLUTE_DATE)) { + TimeUtilConverter timeConverter(context); + std::time_t absoluteDate = timeConverter.toTZDateTimeT(value); + alarm->setAbsoluteDate(absoluteDate); + + if( alarm->getTimeZone().empty() ) { + std::string timeZone = timeConverter.getPropertiesInTZDate(value).timezone; + alarm->setTimeZone(timeZone); + } + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_MINUTES)) { + long minutes = converter.toLong(value); + alarm->setMinutes(minutes); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_DAYS)) { + long days = converter.toLong(value); + alarm->setDays(days); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_METHODS)) { + std::vector methods = converter.toVectorOfInts(value); + alarm->setMethods(methods); + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +} +} +} diff --git a/src/standards/Tizen/Calendar/JSEventAlarm.h b/src/standards/Tizen/Calendar/JSEventAlarm.h new file mode 100755 index 0000000..ae843cc --- /dev/null +++ b/src/standards/Tizen/Calendar/JSEventAlarm.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _JS_EVENT_ALARM_H_ +#define _JS_EVENT_ALARM_H_ + +#include +#include +#include + +using namespace TizenApis::Api::Calendar; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject EventAlarmPrivateObject; + +class JSEventAlarm +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, EventAlarmPtr alarm); + + static EventAlarmPtr getAlarm(JSObjectRef object); + + private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSClassRef m_jsClassRef; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; +} +} +} + +#endif /* _JS_EVENT_ALARM_H_ */ diff --git a/src/standards/Tizen/Calendar/JSEventId.cpp b/src/standards/Tizen/Calendar/JSEventId.cpp new file mode 100755 index 0000000..b4556bf --- /dev/null +++ b/src/standards/Tizen/Calendar/JSEventId.cpp @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "JSEventId.h" +#include +#include +#include +#include +#include +#include + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +#define TIZEN_EVENTID_ATTRIBUTENAME "EventId" +#define TIZEN_EVENTID_UID "uid" +#define TIZEN_EVENTID_RECURRENCEID "recurrenceId" + +JSClassDefinition JSEventId::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_EVENTID_ATTRIBUTENAME, + 0, + m_property, + NULL, //m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSEventId::m_property[] = { + { TIZEN_EVENTID_UID, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_EVENTID_RECURRENCEID, getProperty, setProperty, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSEventId::m_jsClassRef = JSClassCreate( + JSEventId::getClassInfo()); + +const JSClassDefinition* JSEventId::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSEventId::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +EventIdPtr JSEventId::getEventId(JSObjectRef object) +{ + LogDebug("entered"); + EventIdPrivateObject *priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object is null"); + } + EventIdPtr result = priv->getObject(); + if (!result) { + ThrowMsg(NullPointerException, "Private object is null"); + } + return result; +} + +void JSEventId::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("enter"); +} + +void JSEventId::finalize(JSObjectRef object) +{ + LogDebug("enter"); + EventIdPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +JSValueRef JSEventId::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + Converter converter(context); + Try + { + EventIdPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + EventIdPtr eventId = priv->getObject(); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_EVENTID_UID)) { + return converter.toJSValueRef(eventId->getUId()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_EVENTID_RECURRENCEID)) { + if (!eventId) { + Throw(NullPointerException); + } + if (eventId->getRecurrenceId() != 0) { + // Use the global context saved in the event struct. + return JSTZDate::createJSObject(priv->getContext(), eventId->getRecurrenceId(), eventId->getTimeZone()); + } else { + return JSValueMakeUndefined(context); + } + } + } + Catch(Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSEventId::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + Converter converter(context); + Try + { + EventIdPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + EventIdPtr eventId = priv->getObject(); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_EVENTID_UID)) { + std::string uid = converter.toString(value); + eventId->setUId(uid); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_EVENTID_RECURRENCEID)) { + TimeUtilConverter timeConverter(context); + std::time_t recurrenceId = timeConverter.toTZDateTimeT(value); + eventId->setRecurrenceId(recurrenceId); + + if( eventId->getTimeZone().empty() ) { + std::string timeZone = timeConverter.getPropertiesInTZDate(value).timezone; + eventId->setTimeZone(timeZone); + } + return true; + } + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +} +} +} diff --git a/src/standards/Tizen/Calendar/JSEventId.h b/src/standards/Tizen/Calendar/JSEventId.h new file mode 100755 index 0000000..25c2f03 --- /dev/null +++ b/src/standards/Tizen/Calendar/JSEventId.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _JS_EVENT_ID_H_ +#define _JS_EVENT_ID_H_ + +#include +#include +#include +#include +#include + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +typedef PrivateObject EventIdPrivateObject; + +class JSEventId +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static EventIdPtr getEventId(JSObjectRef object); + + private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSClassRef m_jsClassRef; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} +} +} + +#endif /* _JS_EVENT_ID_H_ */ diff --git a/src/standards/Tizen/Calendar/JSRecurrenceRule.cpp b/src/standards/Tizen/Calendar/JSRecurrenceRule.cpp new file mode 100755 index 0000000..5914264 --- /dev/null +++ b/src/standards/Tizen/Calendar/JSRecurrenceRule.cpp @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "JSRecurrenceRule.h" +#include +#include +#include +#include +#include "CalendarConverter.h" +#include +#include + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +JSClassDefinition JSRecurrenceRule::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_RECURRENCE_RULE_ATTRIBUTENAME, + 0, + m_property, + NULL, //m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSRecurrenceRule::m_property[] = { + { TIZEN_RECURRENCE_RULE_FREQUENCY, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_RECURRENCE_RULE_INTERVAL, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_RECURRENCE_RULE_END_DATE, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_RECURRENCE_RULE_OCCURRENCE_COUNT, getProperty, setProperty, kJSPropertyAttributeNone }, +// { TIZEN_RECURRENCE_RULE_DAYS_OF_THE_MONTH, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_RECURRENCE_RULE_DAYS_OF_THE_WEEK, getProperty, setProperty, kJSPropertyAttributeNone }, +// { TIZEN_RECURRENCE_RULE_DAYS_OF_THE_YEAR, getProperty, setProperty, kJSPropertyAttributeNone }, +// { TIZEN_RECURRENCE_RULE_WEEKS_OF_THE_YEAR, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_RECURRENCE_RULE_SET_POSITION, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_RECURRENCE_RULE_EXCEPTIONS, getProperty, setProperty, kJSPropertyAttributeNone }, + + { 0, 0, 0, 0 } +}; + +JSClassRef JSRecurrenceRule::m_jsClassRef = JSClassCreate( + JSRecurrenceRule::getClassInfo()); + +const JSClassDefinition* JSRecurrenceRule::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSRecurrenceRule::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +JSObjectRef JSRecurrenceRule::createJSRecurrenceRule(JSContextRef context, EventRecurrenceRulePtr rule) +{ + RecurrenceRulePrivateObject *priv = new RecurrenceRulePrivateObject(context, rule); + return JSObjectMake(context, getClassRef(), priv); +} + +void JSRecurrenceRule::initialize(JSContextRef context, JSObjectRef object) +{ + LogDebug("enter"); +} + +void JSRecurrenceRule::finalize(JSObjectRef object) +{ + LogDebug("enter"); + RecurrenceRulePrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +JSValueRef JSRecurrenceRule::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + Try + { + RecurrenceRulePrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + EventRecurrenceRulePtr rrule = priv->getObject(); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_FREQUENCY)) { + return converter->toJSValueRef(converter->toTizenValue(rrule->getFrequency())); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_INTERVAL)) { + return converter->toJSValueRef(rrule->getInterval()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_END_DATE)) { + if (!rrule) { + Throw(NullPointerException); + } + if (rrule->getEndDate() != 0) { + // Use the global context saved in the event struct. + return JSTZDate::createJSObject(priv->getContext(), rrule->getEndDate(), rrule->getTimeZone()); + } else { + return JSValueMakeUndefined(context); + } + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_OCCURRENCE_COUNT)) { + return converter->toJSValueRefLong(rrule->getOccurrenceCount()); +// } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_DAYS_OF_THE_MONTH)) { +// return converter->toJSValueRef(rrule->getDaysOfTheMonth()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_DAYS_OF_THE_WEEK)) { + return converter->toJSValueRef(rrule->getDaysOfTheWeek()); +// } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_DAYS_OF_THE_YEAR)) { +// return converter->toJSValueRef(rrule->getDaysOfTheYear()); +// } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_WEEKS_OF_THE_YEAR)) { +// return converter->toJSValueRef(rrule->getWeeksOfTheYear()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_SET_POSITION)) { + return converter->toJSValueRef(rrule->getSetPosition()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_EXCEPTIONS)) { + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + if (NULL == jsResult) { + LogError("Could not create js array object."); + ThrowMsg(NullPointerException, "Could not create js array object"); + } + + for (std::size_t i = 0; i < rrule->getExceptions().size(); ++i) { + JSValueRef tmpVal = JSTZDate::createJSObject(priv->getContext(), rrule->getExceptions().at(i), rrule->getTimeZone()); + if (!JSSetArrayElement(context, jsResult, i, tmpVal)) { + LogError("Could not insert value into js array."); + ThrowMsg(UnknownException, "Could not insert value into js array"); + } + } + + return jsResult; + } + } + Catch(Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSRecurrenceRule::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + CalendarConverterFactory::ConverterType converter = + CalendarConverterFactory::getConverter(context); + Try + { + RecurrenceRulePrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + EventRecurrenceRulePtr rrule = priv->getObject(); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_FREQUENCY)) { + std::string frequency = converter->toString(value); + rrule->setFrequency(converter->toRecurrenceFrequency(frequency)); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_INTERVAL)) { + int interval = converter->toInt(value); + rrule->setInterval(interval); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_END_DATE)) { + TimeUtilConverter timeConverter(context); + std::time_t endDate = timeConverter.toTZDateTimeT(value); + rrule->setEndDate(endDate); + + if( rrule->getTimeZone().empty() ) { + std::string timeZone = timeConverter.getPropertiesInTZDate(value).timezone; + rrule->setTimeZone(timeZone); + } + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_OCCURRENCE_COUNT)) { + long occurrenceCount = converter->toLong(value); + rrule->setOccurrenceCount(occurrenceCount); + return true; +/* } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_DAYS_OF_THE_MONTH)) { + std::vector daysOfTheMonth = converter->toVectorOfInts(value); + rrule->setDaysOfTheMonth(daysOfTheMonth); + return true;*/ + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_DAYS_OF_THE_WEEK)) { + std::vector daysOfTheWeek = converter->toVectorOfStrings(value); + rrule->setDaysOfTheWeek(daysOfTheWeek); + return true; +/* } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_DAYS_OF_THE_YEAR)) { + std::vector daysOfTheYear = converter->toVectorOfInts(value); + rrule->setDaysOfTheYear(daysOfTheYear); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_WEEKS_OF_THE_YEAR)) { + std::vector weekOfTheYear = converter->toVectorOfInts(value); + rrule->setWeeksOfTheYear(weekOfTheYear); + return true;*/ + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_SET_POSITION)) { + return TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::NOT_SUPPORTED_ERROR); + /* + bool setPosition = converter->toBool(value); + rrule->setSetPosition(setPosition);*/ + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_RECURRENCE_RULE_EXCEPTIONS)) { + // Only save the converted time info. + rrule->setExceptions(converter->toVectorOfTimeTFromTZDate(value)); + return true; + } + } + Catch(Exception) + { + LogWarning("trying to set incorrect value"); + } + TizenApis::Commons::JSTizenExceptionFactory::postException(context, exception, TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR); + return false; +} + +} +} +} diff --git a/src/standards/Tizen/Calendar/JSRecurrenceRule.h b/src/standards/Tizen/Calendar/JSRecurrenceRule.h new file mode 100755 index 0000000..d1b90fe --- /dev/null +++ b/src/standards/Tizen/Calendar/JSRecurrenceRule.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _JS_RECURRENCE_RULE_H_ +#define _JS_RECURRENCE_RULE_H_ + +#include +#include +#include +#include +#include +#include + +using namespace TizenApis::Api::Calendar; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +#define TIZEN_RECURRENCE_RULE_ATTRIBUTENAME "RecurrenceRule" +#define TIZEN_RECURRENCE_RULE_FREQUENCY "frequency" +#define TIZEN_RECURRENCE_RULE_INTERVAL "interval" +#define TIZEN_RECURRENCE_RULE_END_DATE "endDate" +#define TIZEN_RECURRENCE_RULE_OCCURRENCE_COUNT "occurrenceCount" +//#define TIZEN_RECURRENCE_RULE_DAYS_OF_THE_MONTH "daysOfTheMonth" +#define TIZEN_RECURRENCE_RULE_DAYS_OF_THE_WEEK "daysOfTheWeek" +//#define TIZEN_RECURRENCE_RULE_DAYS_OF_THE_YEAR "daysOfTheYear" +//#define TIZEN_RECURRENCE_RULE_WEEKS_OF_THE_YEAR "weeksOfTheYear" +#define TIZEN_RECURRENCE_RULE_SET_POSITION "setPositions" +#define TIZEN_RECURRENCE_RULE_EXCEPTIONS "exceptions" + +typedef PrivateObject RecurrenceRulePrivateObject; + +class JSRecurrenceRule +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createJSRecurrenceRule(JSContextRef context, Api::Calendar::EventRecurrenceRulePtr rule); + + private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSClassRef m_jsClassRef; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} +} +} + +#endif /* _JS_RECURRENCE_RULE_H_ */ diff --git a/src/standards/Tizen/Calendar/config.xml b/src/standards/Tizen/Calendar/config.xml new file mode 100755 index 0000000..59ca813 --- /dev/null +++ b/src/standards/Tizen/Calendar/config.xml @@ -0,0 +1,25 @@ + + + + libwrt-plugins-tizen-1.0-calendar.so + calendar.install.uri + SAMSUNG plugin group + SAMSUNG certificate authority + AAAABBBBCCCCDDDEEEE0000 + + + http://tizen.org/api/calendar + calendar.read + calendar.write + + + + http://tizen.org/api/calendar.read + calendar.read + + + + http://tizen.org/api/calendar.write + calendar.write + + \ No newline at end of file diff --git a/src/standards/Tizen/Calendar/plugin_config.cpp b/src/standards/Tizen/Calendar/plugin_config.cpp new file mode 100755 index 0000000..c796d11 --- /dev/null +++ b/src/standards/Tizen/Calendar/plugin_config.cpp @@ -0,0 +1,251 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include + +#include "plugin_config.h" + +#define CALENDAR_FEATURE_API "http://tizen.org/api/calendar" +#define CALENDAR_FEATURE_API_READ "http://tizen.org/api/calendar.read" +#define CALENDAR_FEATURE_API_WRITE "http://tizen.org/api/calendar.write" + +#define CALENDAR_DEVICE_CAP_READ "calendar.read" +#define CALENDAR_DEVICE_CAP_WRITE "calendar.write" + +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +static FunctionMapping createCalendarFunctions(); + +static FunctionMapping CalendarFunctions = + createCalendarFunctions(); + +DEFINE_FUNCTION_GETTER(Calendar, CalendarFunctions); + +static FunctionMapping createCalendarFunctions() +{ + /** + * Device capabilities + */ + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_CALENDAR_READ, CALENDAR_DEVICE_CAP_READ); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_CALENDAR_WRITE, CALENDAR_DEVICE_CAP_WRITE); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_CALENDAR_READ); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_CALENDAR_READ, DEVICE_CAP_CALENDAR_READ); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_CALENDAR_WRITE); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_CALENDAR_WRITE, DEVICE_CAP_CALENDAR_WRITE); + + /** + * Api Features + */ + ACE_CREATE_FEATURE(FEATURE_CALENDAR, CALENDAR_FEATURE_API); + ACE_CREATE_FEATURE(FEATURE_CALENDAR_READ, CALENDAR_FEATURE_API_READ); + ACE_CREATE_FEATURE(FEATURE_CALENDAR_WRITE, CALENDAR_FEATURE_API_WRITE); + + ACE_CREATE_FEATURE_LIST(CALENDAR_FEATURES_CALENDAR_READ_WRITE); + ACE_ADD_API_FEATURE(CALENDAR_FEATURES_CALENDAR_READ_WRITE, + FEATURE_CALENDAR); + ACE_ADD_API_FEATURE(CALENDAR_FEATURES_CALENDAR_READ_WRITE, + FEATURE_CALENDAR_READ); + ACE_ADD_API_FEATURE(CALENDAR_FEATURES_CALENDAR_READ_WRITE, + FEATURE_CALENDAR_WRITE); + + ACE_CREATE_FEATURE_LIST(CALENDAR_FEATURES_CALENDAR_READ); + ACE_ADD_API_FEATURE(CALENDAR_FEATURES_CALENDAR_READ, FEATURE_CALENDAR); + ACE_ADD_API_FEATURE(CALENDAR_FEATURES_CALENDAR_READ, FEATURE_CALENDAR_READ); + + ACE_CREATE_FEATURE_LIST(CALENDAR_FEATURES_CALENDAR_WRITE); + ACE_ADD_API_FEATURE(CALENDAR_FEATURES_CALENDAR_WRITE, FEATURE_CALENDAR); + ACE_ADD_API_FEATURE(CALENDAR_FEATURES_CALENDAR_WRITE, + FEATURE_CALENDAR_WRITE); + + /** + * Functions + */ + + FunctionMapping calendarMapping; + + //getCalendars + AceFunction getCalendarsFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_CALENDARS, + CALENDAR_FUNCTION_API_GET_CALENDARS, + CALENDAR_FEATURES_CALENDAR_READ_WRITE, + DEVICE_LIST_CALENDAR_READ); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_GET_CALENDARS, + getCalendarsFunc)); + + //getDefaultCalendar + AceFunction getDefaultCalendarFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_DEFAULT_CALENDAR, + CALENDAR_FUNCTION_API_GET_DEFAULT_CALENDAR, + CALENDAR_FEATURES_CALENDAR_READ_WRITE, + DEVICE_LIST_CALENDAR_READ); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_GET_DEFAULT_CALENDAR, + getDefaultCalendarFunc)); + + + //find + AceFunction findFunc = ACE_CREATE_FUNCTION( + FUNCTION_FIND, + CALENDAR_FUNCTION_API_FIND, + CALENDAR_FEATURES_CALENDAR_READ, + DEVICE_LIST_CALENDAR_READ); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_FIND, + findFunc)); + + //add + AceFunction addFunc = ACE_CREATE_FUNCTION( + FUNCTION_ADD, + CALENDAR_FUNCTION_API_ADD, + CALENDAR_FEATURES_CALENDAR_WRITE, + DEVICE_LIST_CALENDAR_WRITE); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_ADD, + addFunc)); + + //addBatch + AceFunction addBatchFunc = ACE_CREATE_FUNCTION( + FUNCTION_ADD_BATCH, + CALENDAR_FUNCTION_API_ADD_BATCH, + CALENDAR_FEATURES_CALENDAR_WRITE, + DEVICE_LIST_CALENDAR_WRITE); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_ADD_BATCH, + addBatchFunc)); + + //update + AceFunction updateFunc = ACE_CREATE_FUNCTION( + FUNCTION_UPDATE, + CALENDAR_FUNCTION_API_UPDATE, + CALENDAR_FEATURES_CALENDAR_WRITE, + DEVICE_LIST_CALENDAR_WRITE); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_UPDATE, + updateFunc)); + + //updateBatch + AceFunction updateBatchFunc = ACE_CREATE_FUNCTION( + FUNCTION_UPDATE_BATCH, + CALENDAR_FUNCTION_API_UPDATE_BATCH, + CALENDAR_FEATURES_CALENDAR_WRITE, + DEVICE_LIST_CALENDAR_WRITE); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_UPDATE_BATCH, + updateBatchFunc)); + + //remove + AceFunction removeFunc = ACE_CREATE_FUNCTION( + FUNCTION_REMOVE, + CALENDAR_FUNCTION_API_REMOVE, + CALENDAR_FEATURES_CALENDAR_WRITE, + DEVICE_LIST_CALENDAR_WRITE); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_REMOVE, + removeFunc)); + + //removeBatch + AceFunction removeBatchFunc = ACE_CREATE_FUNCTION( + FUNCTION_REMOVE_BATCH, + CALENDAR_FUNCTION_API_REMOVE_BATCH, + CALENDAR_FEATURES_CALENDAR_WRITE, + DEVICE_LIST_CALENDAR_WRITE); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_REMOVE_BATCH, + removeBatchFunc)); + + //convertFromString + AceFunction convertFromStringFunc = ACE_CREATE_FUNCTION( + FUNCTION_CONVERT_FROM_STRING, + CALENDAR_FUNCTION_API_CONVERT_FROM_STRING, + CALENDAR_FEATURES_CALENDAR_READ_WRITE, + DEVICE_LIST_CALENDAR_READ); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_CONVERT_FROM_STRING, + convertFromStringFunc)); + + //convertToString + AceFunction convertToStringFunc = ACE_CREATE_FUNCTION( + FUNCTION_CONVERT_TO_STRING, + CALENDAR_FUNCTION_API_CONVERT_TO_STRING, + CALENDAR_FEATURES_CALENDAR_READ_WRITE, + DEVICE_LIST_CALENDAR_READ); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_CONVERT_TO_STRING, + convertToStringFunc)); + + //addChangeListener + AceFunction addChangeListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_ADD_CHANGE_LISTENER, + CALENDAR_FUNCTION_API_ADD_CHANGE_LISTENER, + CALENDAR_FEATURES_CALENDAR_READ, + DEVICE_LIST_CALENDAR_READ); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_ADD_CHANGE_LISTENER, + addChangeListenerFunc)); + + //removeChangeListener + AceFunction removeChangeListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_REMOVE_CHANGE_LISTENER, + CALENDAR_FUNCTION_API_REMOVE_CHANGE_LISTENER, + CALENDAR_FEATURES_CALENDAR_READ, + DEVICE_LIST_CALENDAR_READ); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_REMOVE_CHANGE_LISTENER, + removeChangeListenerFunc)); + + //expandEventRecurrence + AceFunction expandEventRecurrenceFunc = ACE_CREATE_FUNCTION( + FUNCTION_EXPAND_EVENT_RECURRENCE, + CALENDAR_FUNCTION_API_EXPAND_EVENT_RECURRENCE, + CALENDAR_FEATURES_CALENDAR_READ, + DEVICE_LIST_CALENDAR_READ); + + calendarMapping.insert(std::make_pair( + CALENDAR_FUNCTION_API_EXPAND_EVENT_RECURRENCE, + expandEventRecurrenceFunc)); + + return calendarMapping; +} + +} +} +} \ No newline at end of file diff --git a/src/standards/Tizen/Calendar/plugin_config.h b/src/standards/Tizen/Calendar/plugin_config.h new file mode 100755 index 0000000..7cccfc0 --- /dev/null +++ b/src/standards/Tizen/Calendar/plugin_config.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _CALENDAR_PLUGIN_CONFIG_H_ +#define _CALENDAR_PLUGIN_CONFIG_H_ + +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +#define CALENDAR_FUNCTION_API_GET_CALENDARS "getCalendars" +#define CALENDAR_FUNCTION_API_GET_DEFAULT_CALENDAR "getDefaultCalendar" +#define CALENDAR_FUNCTION_API_ADD "add" +#define CALENDAR_FUNCTION_API_ADD_BATCH "addBatch" +#define CALENDAR_FUNCTION_API_UPDATE "update" +#define CALENDAR_FUNCTION_API_UPDATE_BATCH "updateBatch" +#define CALENDAR_FUNCTION_API_REMOVE "remove" +#define CALENDAR_FUNCTION_API_REMOVE_BATCH "removeBatch" +#define CALENDAR_FUNCTION_API_FIND "find" +#define CALENDAR_FUNCTION_API_CONVERT_FROM_STRING "convertFromString" +#define CALENDAR_FUNCTION_API_CONVERT_TO_STRING "convertToString" +#define CALENDAR_FUNCTION_API_ADD_CHANGE_LISTENER "addChangeListener" +#define CALENDAR_FUNCTION_API_REMOVE_CHANGE_LISTENER "removeChangeListener" +#define CALENDAR_FUNCTION_API_EXPAND_EVENT_RECURRENCE "expandEventRecurrence" + +DECLARE_FUNCTION_GETTER(Calendar); + +#define CALENDAR_CHECK_ACCESS(globalContext, functionName) \ + aceCheckAccess >( \ + globalContext, \ + getCalendarFunctionData, \ + functionName) + +} +} +} + +#endif // _CALENDAR_PLUGIN_CONFIG_H_ diff --git a/src/standards/Tizen/Calendar/plugin_initializer.cpp b/src/standards/Tizen/Calendar/plugin_initializer.cpp new file mode 100755 index 0000000..d3e5494 --- /dev/null +++ b/src/standards/Tizen/Calendar/plugin_initializer.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include + +#include +#include +#include +#include "JSCalendarManager.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Calendar { + +void on_widget_start_callback(int widgetId, + JavaScriptContext context, + const engine_interface_t *interface) +{ + LogDebug("[Tizen\\calendar] on_widget_start_callback (" << widgetId << ")"); + Try + { + WrtDeviceApis::Commons::WrtWrappersMgr::getInstance().registerWrapper( + widgetId, + context, + interface); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("Wrt wrapper registration failed"); + } +} + +void on_widget_stop_callback(int widgetId) +{ + LogDebug("[Tizen\\calendar] on_widget_stop_callback (" << widgetId << ")"); + Try + { + WrtDeviceApis::Commons::WrtWrappersMgr::getInstance().removeWrapper(widgetId); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("Wrt wrapper removal failed"); + } +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, + "calendar", + JSCalendarManager::getClassRef(), + NULL) +PLUGIN_CLASS_MAP_END + +} +} +} + diff --git a/src/standards/Tizen/Call/CMakeLists.txt b/src/standards/Tizen/Call/CMakeLists.txt new file mode 100755 index 0000000..bfa3352 --- /dev/null +++ b/src/standards/Tizen/Call/CMakeLists.txt @@ -0,0 +1,30 @@ +set(TARGET_NAME "wrt-plugins-tizen-1.0-call") + +include_directories(${INCLUDES_PLATFORM_IMPLEMENTATION_CALL}) + +set(SRCS + ${SRCS_PLATFORM_API_CALL} + ${SRCS_PLATFORM_IMPLEMENTATION_CALL} + ${SRCS_PLATFORM_API_FILTER} + JSCallApi.cpp + JSCallHistory.cpp + JSCallHistoryEntry.cpp + Converter.cpp + ResponseDispatcher.cpp + plugin_initializer.cpp + plugin_config.cpp + ../Tizen/FilterConverter.cpp + ../Common/JSTizenException.cpp + ../Common/TizenExceptionData.cpp + ../Common/JSTizenExceptionFactory.cpp +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMON} + ${LIBS_PLATFORM_IMPLEMENTATION_CALL} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION tizen-1.0-call) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION tizen-1.0-call) + diff --git a/src/standards/Tizen/Call/Converter.cpp b/src/standards/Tizen/Call/Converter.cpp new file mode 100755 index 0000000..0e1d4ea --- /dev/null +++ b/src/standards/Tizen/Call/Converter.cpp @@ -0,0 +1,328 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "Converter.h" +#include + +#include +#include +#include +#include +#include +#include "JSCallHistoryEntry.h" + +#define CH_ENTRY_ID "entryId" +#define CH_ACCOUNT_ID "accountId" +#define CH_CALL_TYPE "callType" +#define CH_REMOTE_PARTY "remoteParty" +#define CH_CONTACT_ID "contactId" +#define CH_CONTACT_DETAILS "contactDetails" +#define CH_FORWARDEDFROM "forwardedFrom" +#define CH_START_TIME "startTime" +#define CH_DURATION "duration" +#define CH_END_REASON "endReason" +#define CH_USED_CAPABILITIES "usedCapabilities" +#define CH_KIND "kind" +#define CH_TAGS "tags" +#define CH_DIRECTION "direction" +#define CH_RECORDING "recording" +#define CH_COST "cost" +#define CH_CURRENCY "currency" + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Api::Call; + +namespace TizenApis { +namespace Tizen1_0 { +std::vector Converter::m_allowedCallHistoryEntryProperties; + +Converter::Converter(JSContextRef context) : WrtDeviceApis::CommonsJavaScript::Converter(context) +{ + static bool init = initializeAllowedProperties(); + (void) init; +} + +std::vector Converter::toVectorOfULongs(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toULong); +} + +CallHistoryEntryList Converter::toVectorOfCallHistoryEntryProperties(const JSValueRef& arg) +{ + if (JSValueIsNull(m_context, arg) || JSValueIsUndefined(m_context, arg)) { + ThrowMsg(Commons::InvalidArgumentException, "Undefined history entry"); + } + + if (!JSIsArrayValue(m_context, arg)) { + ThrowMsg(Commons::ConversionException, "Argument is not an JS array."); + } + + try { + CallHistoryEntryList result; + JSObjectRef objArg = toJSObjectRef(arg); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, objArg); ++i) { + JSValueRef element = JSGetArrayElement(m_context, objArg, i); + result.push_back(toCallHistoryEntryProperties(element)); + } + return result; + } catch (Commons::ConversionException& ex) { + ThrowMsg(Commons::ConversionException, ex.GetMessage()); + } catch (Commons::InvalidArgumentException& ex) { + ThrowMsg(Commons::InvalidArgumentException, ex.GetMessage()); + } catch (Commons::Exception& ex) { + ThrowMsg(Commons::Exception, ex.GetMessage()); + } + +} + +stringArrayPtr Converter::toCallHistoryEntryStringArray(const JSValueRef &jsValue) +{ + stringArrayPtr result(new stringArray()); + try { + if (!JSValueIsNull(m_context, jsValue)) { + JSObjectRef jsObject = toJSObjectRef(jsValue); + + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toString(element)); + } + } + } catch (Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + } + return result; +} + +CallHistoryEntryPropertiesPtr Converter::toCallHistoryEntryProperties(const JSValueRef &jsValue) +{ + Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedCallHistoryEntryProperties, jsValue)) { + ThrowMsg(Commons::InvalidArgumentException, "Wrong attribute of call history entry"); + } + + const ScopedJSStringRef entryIdStr(JSStringCreateWithUTF8CString(CH_ENTRY_ID)); + const ScopedJSStringRef accountIdStr(JSStringCreateWithUTF8CString(CH_ACCOUNT_ID)); + const ScopedJSStringRef callTypeStr(JSStringCreateWithUTF8CString(CH_CALL_TYPE)); + const ScopedJSStringRef remotePartyStr(JSStringCreateWithUTF8CString(CH_REMOTE_PARTY)); + const ScopedJSStringRef contactIdStr(JSStringCreateWithUTF8CString(CH_CONTACT_ID)); + const ScopedJSStringRef contactDetailsStr(JSStringCreateWithUTF8CString(CH_CONTACT_DETAILS)); + const ScopedJSStringRef forwardedFromStr(JSStringCreateWithUTF8CString(CH_FORWARDEDFROM)); + const ScopedJSStringRef startTimeStr(JSStringCreateWithUTF8CString(CH_START_TIME)); + const ScopedJSStringRef durationStr(JSStringCreateWithUTF8CString(CH_DURATION)); + const ScopedJSStringRef endReasonStr(JSStringCreateWithUTF8CString(CH_END_REASON)); + const ScopedJSStringRef usedCapabilitiesStr(JSStringCreateWithUTF8CString(CH_USED_CAPABILITIES)); + const ScopedJSStringRef kindStr(JSStringCreateWithUTF8CString(CH_KIND)); + const ScopedJSStringRef directionStr(JSStringCreateWithUTF8CString(CH_DIRECTION)); + const ScopedJSStringRef recordingStr(JSStringCreateWithUTF8CString(CH_RECORDING)); + const ScopedJSStringRef costStr(JSStringCreateWithUTF8CString(CH_COST)); + const ScopedJSStringRef currencyStr(JSStringCreateWithUTF8CString(CH_CURRENCY)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef jEntryId = JSObjectGetProperty(m_context, jsObject, entryIdStr.get(), NULL); + JSValueRef jAccountId = JSObjectGetProperty(m_context, jsObject, accountIdStr.get(), NULL); + JSValueRef jCallType = JSObjectGetProperty(m_context, jsObject, callTypeStr.get(), NULL); + JSValueRef jRemoteParty = JSObjectGetProperty(m_context, jsObject, remotePartyStr.get(), NULL); + JSValueRef jContactId = JSObjectGetProperty(m_context, jsObject, contactIdStr.get(), NULL); + JSValueRef jContactDetails = JSObjectGetProperty(m_context, jsObject, contactDetailsStr.get(), NULL); + JSValueRef jForwardedFrom = JSObjectGetProperty(m_context, jsObject, forwardedFromStr.get(), NULL); + JSValueRef jStartTime = JSObjectGetProperty(m_context, jsObject, startTimeStr.get(), NULL); + JSValueRef jDuration = JSObjectGetProperty(m_context, jsObject, durationStr.get(), NULL); + JSValueRef jEndReason = JSObjectGetProperty(m_context, jsObject, endReasonStr.get(), NULL); + JSValueRef jUsedCapabilities = JSObjectGetProperty(m_context, jsObject, usedCapabilitiesStr.get(), NULL); + JSValueRef jKind = JSObjectGetProperty(m_context, jsObject, kindStr.get(), NULL); + JSValueRef jDirection = JSObjectGetProperty(m_context, jsObject, directionStr.get(), NULL); + JSValueRef jRecording = JSObjectGetProperty(m_context, jsObject, recordingStr.get(), NULL); + JSValueRef jCost = JSObjectGetProperty(m_context, jsObject, costStr.get(), NULL); + JSValueRef jCurrency = JSObjectGetProperty(m_context, jsObject, currencyStr.get(), NULL); + + unsigned long entryId; + std::string accountId; + std::string callType; + std::string remoteParty; + std::string contactId; + std::string contactDetails; + std::string forwardedFrom; + time_t startTime; + unsigned long duration; + std::string endReason; + stringArrayPtr usedCapabilities; + std::string kind; + std::string direction; + stringArrayPtr recording; + unsigned long cost; + std::string currency; + + CallHistoryEntryPropertiesPtr result = CallHistoryEntryPropertiesPtr(new CallHistoryEntryProperties()); + + if (!result) { + Throw(Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, jEntryId)) { + entryId = toULong(jEntryId); + result->setEntryId(entryId); + } else { + ThrowMsg(Commons::InvalidArgumentException, "Undefined history entry"); + } + + if (!JSValueIsUndefined(m_context, jAccountId)) { + accountId = toString(jAccountId); + result->setAccountId(accountId); + } + + if (!JSValueIsUndefined(m_context, jCallType)) { + callType = toString(jCallType); + result->setCallType(callType); + } + + if (!JSValueIsUndefined(m_context, jRemoteParty)) { + remoteParty = toString(jRemoteParty); + result->setRemoteParty(remoteParty); + } else { + ThrowMsg(Commons::InvalidArgumentException, "Undefined history entry"); + } + + if (!JSValueIsUndefined(m_context, jContactId)) { + contactId = toString(jContactId); + result->setContactId(contactId); + } + + if (!JSValueIsUndefined(m_context, jContactDetails)) { + contactDetails = toString(jContactDetails); + result->setContactDetails(contactDetails); + } + + if (!JSValueIsUndefined(m_context, jForwardedFrom)) { + forwardedFrom = toString(jForwardedFrom); + result->setForwardedFrom(forwardedFrom); + } + + if (!JSValueIsUndefined(m_context, jStartTime)) { + startTime = toDateTimeT(jStartTime); + result->setStartTime(startTime); + } + + if (!JSValueIsUndefined(m_context, jDuration)) { + duration = toULong(jDuration); + result->setDuration(duration); + } + + if (!JSValueIsUndefined(m_context, jEndReason)) { + endReason = toString(jEndReason); + result->setEndReason(endReason); + } + + if (!JSValueIsUndefined(m_context, jUsedCapabilities)) { + usedCapabilities = toCallHistoryEntryStringArray(jUsedCapabilities); + result->setUsedCapabilities(usedCapabilities); + } + + if (!JSValueIsUndefined(m_context, jKind)) { + kind = toString(jKind); + result->setKind(kind); + } + + if (!JSValueIsUndefined(m_context, jDirection)) { + direction = toString(jDirection); + result->setDirection(direction); + } + + if (!JSValueIsUndefined(m_context, jRecording)) { + recording = toCallHistoryEntryStringArray(jRecording); + result->setRecording(recording); + } + + if (!JSValueIsUndefined(m_context, jCost)) { + cost = toULong(jCost); + result->setCost(cost); + } + + if (!JSValueIsUndefined(m_context, jCurrency)) { + currency = toString(jCurrency); + result->setCurrency(currency); + } + + return result; +} + +JSValueRef Converter::toJSValueRef(const Api::Call::CallHistoryEntryListPtr& arg, JSContextRef context) +{ + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + if (!jsResult) { + ThrowMsg(Commons::ConversionException, "Could not create js array object"); + } + Api::Call::CallHistoryEntryProperties tmpCallEntry; + + for (size_t i = 0; i < (*arg).size(); i++) { + tmpCallEntry = *((*arg)[i]); + JSObjectRef jsObject = JSCallHistoryEntry::createJSObject(context, tmpCallEntry); + if (!jsObject) { + ThrowMsg(Commons::ConversionException, "Could not create JS object."); + } + + if (!JSSetArrayElement(m_context, jsResult, i, jsObject)) { + ThrowMsg(Commons::ConversionException, "Could not insert value into js array"); + } + } + return jsResult; +} + +JSValueRef Converter::toJSValueRef(const Api::Call::stringArrayPtr &arg, JSContextRef context) +{ + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + if (!jsResult) { + ThrowMsg(Commons::ConversionException, "Could not create js array object"); + } + + for (size_t i = 0; i < (*arg).size(); i++) { + if (!JSSetArrayElement(m_context, jsResult, i, toJSValueRef((*arg)[i]))) { + ThrowMsg(Commons::ConversionException, "Could not insert value into js array"); + } + } + + return jsResult; +} + +bool Converter::initializeAllowedProperties() +{ + m_allowedCallHistoryEntryProperties.push_back(CH_ENTRY_ID); + m_allowedCallHistoryEntryProperties.push_back(CH_ACCOUNT_ID); + m_allowedCallHistoryEntryProperties.push_back(CH_CALL_TYPE); + m_allowedCallHistoryEntryProperties.push_back(CH_REMOTE_PARTY); + m_allowedCallHistoryEntryProperties.push_back(CH_CONTACT_ID); + m_allowedCallHistoryEntryProperties.push_back(CH_CONTACT_DETAILS); + m_allowedCallHistoryEntryProperties.push_back(CH_FORWARDEDFROM); + m_allowedCallHistoryEntryProperties.push_back(CH_START_TIME); + m_allowedCallHistoryEntryProperties.push_back(CH_DURATION); + m_allowedCallHistoryEntryProperties.push_back(CH_END_REASON); + m_allowedCallHistoryEntryProperties.push_back(CH_USED_CAPABILITIES); + m_allowedCallHistoryEntryProperties.push_back(CH_KIND); + m_allowedCallHistoryEntryProperties.push_back(CH_DIRECTION); + m_allowedCallHistoryEntryProperties.push_back(CH_RECORDING); + m_allowedCallHistoryEntryProperties.push_back(CH_COST); + m_allowedCallHistoryEntryProperties.push_back(CH_CURRENCY); + + return true; + +} + +} // Tizen1_0 +} // TizenApis + diff --git a/src/standards/Tizen/Call/Converter.h b/src/standards/Tizen/Call/Converter.h new file mode 100755 index 0000000..6a87a9d --- /dev/null +++ b/src/standards/Tizen/Call/Converter.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZEN_APIS_CALL_CONVERTER_H_ +#define TIZEN_APIS_CALL_CONVERTER_H_ + +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +class Converter : public WrtDeviceApis::CommonsJavaScript::Converter +{ +public: + using WrtDeviceApis::CommonsJavaScript::Converter::toJSValueRef; + +public: + explicit Converter(JSContextRef context); + + std::vector toVectorOfULongs(const JSValueRef& arg); + + Api::Call::CallHistoryEntryList toVectorOfCallHistoryEntryProperties(const JSValueRef& arg); + + Api::Call::stringArrayPtr toCallHistoryEntryStringArray(const JSValueRef &jsValue); + + Api::Call::CallHistoryEntryPropertiesPtr toCallHistoryEntryProperties(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const Api::Call::CallHistoryEntryListPtr &arg, JSContextRef context); + + JSValueRef toJSValueRef(const Api::Call::stringArrayPtr &arg, JSContextRef context); + +private: + bool initializeAllowedProperties(); + static std::vector m_allowedCallHistoryEntryProperties; +}; + +typedef WrtDeviceApis::CommonsJavaScript::ConverterFactory ConverterFactory; +typedef ConverterFactory::ConverterType ConverterPtr; +} +} + +#endif \ No newline at end of file diff --git a/src/standards/Tizen/Call/JSCallApi.cpp b/src/standards/Tizen/Call/JSCallApi.cpp new file mode 100755 index 0000000..fe11429 --- /dev/null +++ b/src/standards/Tizen/Call/JSCallApi.cpp @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include + +#include +#include +#include +#include +#include + +#include "JSCallApi.h" +#include "JSCallHistory.h" +#include "Converter.h" + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassRef JSCallApi::m_jsClassRef = NULL; + +JSClassDefinition JSCallApi::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "call", + NULL, + m_property, + NULL, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + hasInstance, + NULL +}; + +JSStaticValue JSCallApi::m_property[] = { + { "history", getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSCallApi::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSCallApi::getClassInfo(){ + return &m_classInfo; +} + +void JSCallApi::initialize(JSContextRef context, JSObjectRef object) { + JSCallApiPriv *priv = static_cast(JSObjectGetPrivate(object)); + + if (priv == NULL) { + priv = new JSCallApiPriv(context); + + if(!JSObjectSetPrivate(object, static_cast(priv))) { + LogError("Object can't store private data."); + delete priv; + } + } +} + +void JSCallApi::finalize(JSObjectRef object) { + JSCallApiPriv* priv = static_cast(JSObjectGetPrivate(object)); + + if (priv != NULL) { + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +JSValueRef JSCallApi::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + JSCallApiPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + return JSValueMakeUndefined(context); + } + + JSContextRef globalContext = priv->getContext(); + + try { + Converter convert(context); + if(JSStringIsEqualToUTF8CString(propertyName, "history")) { + return TizenApis::Tizen1_0::JSCallHistory::createJSObject(globalContext, object); + } + } catch(Commons::Exception) { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCallApi::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +} +} + diff --git a/src/standards/Tizen/Call/JSCallApi.h b/src/standards/Tizen/Call/JSCallApi.h new file mode 100755 index 0000000..c5c1c75 --- /dev/null +++ b/src/standards/Tizen/Call/JSCallApi.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZEN_APIS_JS_CALLAPI_H_ +#define TIZEN_APIS_JS_CALLAPI_H_ + +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSCallApiPriv; + +class JSCallApi +{ +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + +private: + static void initialize(JSContextRef context, JSObjectRef object); + + static void finalize(JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + static bool hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception); + + static JSClassDefinition m_classInfo; + + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + +}; + +} +} + +#endif + diff --git a/src/standards/Tizen/Call/JSCallHistory.cpp b/src/standards/Tizen/Call/JSCallHistory.cpp new file mode 100755 index 0000000..61bf5a3 --- /dev/null +++ b/src/standards/Tizen/Call/JSCallHistory.cpp @@ -0,0 +1,362 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "JSCallHistoryEntry.h" +#include "JSCallHistory.h" +#include "ResponseDispatcher.h" +#include "Converter.h" +#include "plugin_config.h" + +using namespace std; +using namespace DPL; +using namespace TizenApis::Api::Tizen; +using namespace TizenApis::Api::Call; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Tizen1_0::Tizen; +using namespace TizenApis::Commons; + +#define STR_CALL_TYPE_UNKNOWN "CALL_TYPE_UNKNOWN" +#define STR_CALL_TYPE_AUDIO "CALL_TYPE_AUDIO" +#define STR_CALL_TYPE_VIDEO "CALL_TYPE_VIDEO" + +#define STR_CALL_STATE_UNKNOWN "CALL_STATE_UNKNOWN" +#define STR_CALL_STATE_INCOMING "CALL_STATE_INCOMING" +#define STR_CALL_STATE_OUTGOING "CALL_STATE_OUTGOING" +#define STR_CALL_STATE_MISSED_CHECKED "CALL_STATE_MISSED_CHECKED" +#define STR_CALL_STATE_MISSED_UNCHECKED "CALL_STATE_MISSED_UNCHECKED" +#define STR_CALL_STATE_REJECTED "CALL_STATE_REJECTED" +#define STR_CALL_STATE_BLOCKED "CALL_STATE_BLOCKED" + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassRef JSCallHistory::m_jsClassRef = NULL; + +JSClassDefinition JSCallHistory::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "callhistory", + NULL, + m_property, + m_function, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + hasInstance, + NULL +}; + +JSStaticValue JSCallHistory::m_property[] = { + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSCallHistory::m_function[] = +{ + { "find", JSCallHistory::find, kJSPropertyAttributeNone }, + { "remove", JSCallHistory::remove, kJSPropertyAttributeNone }, + { "removeBatch", JSCallHistory::removeBatch, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef JSCallHistory::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSCallHistory::getClassInfo(){ + return &m_classInfo; +} + +void JSCallHistory::initialize(JSContextRef context, JSObjectRef object) { + JSCallHistoryPriv* priv = static_cast(JSObjectGetPrivate(object)); + + if (priv == NULL) { + ICallHistoryPtr CallHistory(CallHistoryFactory::getInstance().getCallHistoryObject()); + priv = new JSCallHistoryPriv(context, CallHistory); + if(!JSObjectSetPrivate(object, static_cast(priv))) { + delete priv; + } + } +} + +void JSCallHistory::finalize(JSObjectRef object) { + JSCallHistoryPriv* priv = static_cast(JSObjectGetPrivate(object)); + if (priv != NULL) { + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +JSObjectRef JSCallHistory::createJSObject(JSContextRef context, JSObjectRef object) +{ + ICallHistoryPtr CallHistory(CallHistoryFactory::getInstance().getCallHistoryObject()); + JSCallHistoryPriv* priv = new JSCallHistoryPriv(context, CallHistory); + + return JSObjectMake(context, getClassRef(), priv); +} + +bool JSCallHistory::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSCallHistory::find(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) { + + if (argumentCount < 1) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid values error"); + } + + JSCallHistoryPriv *priv = static_cast (JSObjectGetPrivate(thisObject)); + JSContextRef gContext = priv->getContext(); + + assert(priv && "Invalid private pointer."); + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Validator check(context, exception); + + try { + FilterConverterFactory::ConverterType filterConverter = FilterConverterFactory::getConverter(context); + + JSCallbackManagerPtr cbm(JSCallbackManager::createObject(gContext)); + if (cbm != NULL) { + cbm->setObject(thisObject); + } + + if (argumentCount >= 2) { + if (!JSValueIsNull(context, arguments[1]) && !JSValueIsUndefined(context, arguments[1])) { + if (!JSObjectIsFunction(context, converter.toJSObjectRef(arguments[1]))) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type missmatch error : error callback "); + } + cbm->setOnError(arguments[1]); + } + } + + if (argumentCount >= 1) { + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0])) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid values error : success callback "); + } else if (!JSObjectIsFunction(context, converter.toJSObjectRef(arguments[0]))) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type missmatch error : success callback "); + } + cbm->setOnSuccess(arguments[0]); + } + + if (argumentCount >= 3) { + if (!JSValueIsNull(context, arguments[2]) && !JSValueIsUndefined(context, arguments[2])) { + if (!JSValueIsObject(context, arguments[2])) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type missmatch error : filter"); + } + } + } + + AceSecurityStatus status = CALL_HISTORY_CHECK_ACCESS( + gContext, + CALL_HISTORY_FUNCTION_API_FIND); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + EventFindCallHistoryPtr event(new EventFindCallHistory()); + ICallHistoryPtr callHistory(priv->getObject()); + event->setPrivateData(StaticPointerCast (cbm)); + event->setForAsynchronousCall(&ResponseDispatcher::getInstance()); + + if (argumentCount >= 3) { + if (!check.isNullOrUndefined(arguments[2])) { + FilterPtr filter = filterConverter->toFilter(arguments[2]); + event ->setFilter(filter); + } + } + + if (argumentCount >= 4) { + if (!check.isNullOrUndefined(arguments[3])) { + event->setSortMode(filterConverter->toSortModeArray(arguments[3])); + } + } + + if (argumentCount >= 5) { + if (!check.isNullOrUndefined(arguments[4])) { + event->setLimit(converter.toULong(arguments[4])); + } + } + + if (argumentCount >= 6) { + if (!check.isNullOrUndefined(arguments[5])) { + event->setOffset(converter.toULong(arguments[5])); + } + } + + callHistory->find(event); + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::IO_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::PlatformException& ex) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::IO_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, ex.GetMessage()); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSCallHistory::remove(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) { + + if (argumentCount < 1) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid values error"); + } + + JSCallHistoryPriv *priv = static_cast (JSObjectGetPrivate(thisObject)); + JSContextRef gContext = priv->getContext(); + + assert(priv && "Invalid private pointer."); + Converter converter(context); + Validator check(context, exception); + + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0])) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid values error : CallHistoryEntry"); + } else if (!JSValueIsObject(context, arguments[0])) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type missmatch error : CallHistoryEntry"); + } + + try { + AceSecurityStatus status = CALL_HISTORY_CHECK_ACCESS( + gContext, + CALL_HISTORY_FUNCTION_API_REMOVE); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ICallHistoryPtr callHistory(priv->getObject()); + CallHistoryEntryPropertiesPtr entry = converter.toCallHistoryEntryProperties(arguments[0]); + callHistory->remove(entry->getEntryId()); + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::IO_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::PlatformException& ex) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::IO_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, ex.GetMessage()); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSCallHistory::removeBatch(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) { + + if (argumentCount < 1) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid values error"); + } + + JSCallHistoryPriv *priv = static_cast (JSObjectGetPrivate(thisObject)); + JSContextRef gContext = priv->getContext(); + + assert(priv && "Invalid private pointer."); + Converter converter(context); + Validator check(context, exception); + + if (!JSIsArrayValue(context, arguments[0])) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type missmatch error : CallHistoryEntry array"); + } + + try { + JSCallbackManagerPtr cbm(JSCallbackManager::createObject(gContext)); + if (cbm != NULL) { + cbm->setObject(thisObject); + } + + if (argumentCount >= 3) { + if (!JSValueIsNull(context, arguments[2]) && !JSValueIsUndefined(context, arguments[2])) { + if (!JSObjectIsFunction(context, converter.toJSObjectRef(arguments[2]))) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type missmatch error : error callback"); + } + cbm->setOnError(arguments[2]); + } + } + + if (argumentCount >= 2) { + if (!JSValueIsNull(context, arguments[1]) && !JSValueIsUndefined(context, arguments[1])) { + if (!JSObjectIsFunction(context, converter.toJSObjectRef(arguments[1]))) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type missmatch error : success callback"); + } + cbm->setOnSuccess(arguments[1]); + } + } + + AceSecurityStatus status = CALL_HISTORY_CHECK_ACCESS( + gContext, + CALL_HISTORY_FUNCTION_API_REMOVE_BATCH); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + EventRemoveBatchPtr event(new EventRemoveBatch()); + ICallHistoryPtr callHistory(priv->getObject()); + + event->setPrivateData(StaticPointerCast (cbm)); + event->setForAsynchronousCall(&ResponseDispatcher::getInstance()); + + CallHistoryEntryList entryList = converter.toVectorOfCallHistoryEntryProperties(arguments[0]); + + std::vector entryIds; + + if (entryList.size() > 0) { + for (unsigned int i = 0; i < entryList.size(); i++) { + entryIds.push_back(entryList[i]->getEntryId()); + } + event->setEntryIds(entryIds); + callHistory->removeBatch(event); + } else { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid values error : Entry array is null"); + } + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::IO_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::PlatformException& ex) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::IO_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, ex.GetMessage()); + } + + return JSValueMakeUndefined(context); +} + +} +} + diff --git a/src/standards/Tizen/Call/JSCallHistory.h b/src/standards/Tizen/Call/JSCallHistory.h new file mode 100755 index 0000000..4394dcb --- /dev/null +++ b/src/standards/Tizen/Call/JSCallHistory.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZEN_APIS_JS_CALLHISTORY_H_ +#define TIZEN_APIS_JS_CALLHISTORY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSCallHistoryPriv; + +class JSCallHistory +{ +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, JSObjectRef object); +private: + static void initialize(JSContextRef context, JSObjectRef object); + + static void finalize(JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + static bool hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception); + + + static JSValueRef find(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef remove(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef removeBatch(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSClassDefinition m_classInfo; + + static JSStaticValue m_property[]; + + static JSStaticFunction m_function[]; + + static JSClassRef m_jsClassRef; + +}; + +} +} + +#endif + diff --git a/src/standards/Tizen/Call/JSCallHistoryEntry.cpp b/src/standards/Tizen/Call/JSCallHistoryEntry.cpp new file mode 100755 index 0000000..a5a0595 --- /dev/null +++ b/src/standards/Tizen/Call/JSCallHistoryEntry.cpp @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include "JSCallHistoryEntry.h" +#include "Converter.h" + +namespace TizenApis { +namespace Tizen1_0 { + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace Api::Call; + +#define STR_ENTRY_ID "entryId" +#define STR_ACCOUNT_ID "accountId" +#define STR_CALL_TYPE "callType" +#define STR_REMOTE_PARTY "remoteParty" +#define STR_CONTACT_ID "contactId" +#define STR_CONTACT_DETAILS "contactDetails" +#define STR_FORWARDEDFROM "forwardedFrom" +#define STR_START_TIME "startTime" +#define STR_DURATION "duration" +#define STR_END_REASON "endReason" +#define STR_USED_CAPABILITIES "usedCapabilities" +#define STR_KIND "kind" +#define STR_DIRECTION "direction" +#define STR_RECORDING "recording" +#define STR_COST "cost" +#define STR_CURRENCY "currency" + +JSClassDefinition JSCallHistoryEntry::m_classInfo = { + 0, + kJSClassAttributeNone, + "callhistoryentry", + 0, + m_property, + 0, + initialize, + finalize, + NULL, //HasProperty, + getProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, + NULL, //ConvertToType +}; + +JSStaticValue JSCallHistoryEntry::m_property[] = { + { STR_ENTRY_ID, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STR_ACCOUNT_ID, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STR_CALL_TYPE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STR_REMOTE_PARTY, getProperty, NULL, kJSPropertyAttributeNone }, + { STR_CONTACT_ID, getProperty, NULL, kJSPropertyAttributeNone }, + { STR_CONTACT_DETAILS, getProperty, NULL, kJSPropertyAttributeNone }, + { STR_FORWARDEDFROM, getProperty, NULL, kJSPropertyAttributeNone }, + { STR_START_TIME, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STR_DURATION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STR_END_REASON, getProperty, NULL, kJSPropertyAttributeNone }, + { STR_USED_CAPABILITIES, getProperty, NULL, kJSPropertyAttributeNone }, + { STR_KIND, getProperty, NULL, kJSPropertyAttributeNone }, + { STR_DIRECTION, getProperty, NULL, kJSPropertyAttributeNone }, + { STR_RECORDING, getProperty, NULL, kJSPropertyAttributeNone }, + { STR_COST, getProperty, NULL, kJSPropertyAttributeNone }, + { STR_CURRENCY, getProperty, NULL, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSCallHistoryEntry::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSCallHistoryEntry::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSCallHistoryEntry::m_jsClassRef = JSClassCreate(JSCallHistoryEntry::getClassInfo()); + +JSObjectRef JSCallHistoryEntry::createJSObject(JSContextRef context, + const CallHistoryEntryProperties &callInfo) +{ + std::auto_ptr callHistoryEntryProps(new CallHistoryEntryProperties(callInfo)); + JSCallHistoryEntryPriv *priv = new JSCallHistoryEntryPriv(context, callHistoryEntryProps.get()); + callHistoryEntryProps.release(); + if (!priv) { + ThrowMsg(Commons::NullPointerException, "Can not new an object"); + } + return JSObjectMake(context, getClassRef(), priv); +} + +void JSCallHistoryEntry::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSCallHistoryEntry::finalize(JSObjectRef object) +{ + JSCallHistoryEntryPriv* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + +JSValueRef JSCallHistoryEntry::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + JSCallHistoryEntryPriv *priv = static_cast(JSObjectGetPrivate(object)); + assert(priv && "Private object not set."); + + try { + CallHistoryEntryProperties *callInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, STR_ENTRY_ID)) { + return convert.toJSValueRef(callInfo->getEntryId()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_ACCOUNT_ID)) { + return convert.toJSValueRef(callInfo->getAccountId()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_CALL_TYPE)) { + return convert.toJSValueRef(callInfo->getCallType()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_REMOTE_PARTY)) { + return convert.toJSValueRef(callInfo->getRemoteParty()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_CONTACT_ID)) { + return convert.toJSValueRef(callInfo->getContactId()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_CONTACT_DETAILS)) { + return convert.toJSValueRef(callInfo->getContactDetails()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_FORWARDEDFROM)) { + return convert.toJSValueRef(callInfo->getForwardedFrom()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_START_TIME)) { + return convert.toJSValueRef(callInfo->getStartTime()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_DURATION)) { + return convert.toJSValueRef(callInfo->getDuration()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_END_REASON)) { + return convert.toJSValueRef(callInfo->getEndReason()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_USED_CAPABILITIES)) { + return convert.toJSValueRef(callInfo->getUsedCapabilities(), context); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_KIND)) { + return convert.toJSValueRef(callInfo->getKind()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_DIRECTION)) { + return convert.toJSValueRef(callInfo->getDirection()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_DURATION)) { + return convert.toJSValueRef(callInfo->getDuration()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_RECORDING)) { + return convert.toJSValueRef(callInfo->getRecording(), context); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_COST)) { + return convert.toJSValueRef(callInfo->getCost()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_CURRENCY)) { + return convert.toJSValueRef(callInfo->getCurrency()); + } + } catch(Commons::Exception) { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSCallHistoryEntry::hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} +} +} + diff --git a/src/standards/Tizen/Call/JSCallHistoryEntry.h b/src/standards/Tizen/Call/JSCallHistoryEntry.h new file mode 100755 index 0000000..651a29a --- /dev/null +++ b/src/standards/Tizen/Call/JSCallHistoryEntry.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_TIZEN_JS_CALLINFO_H_ +#define TIZENAPIS_TIZEN_JS_CALLINFO_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSCallHistoryEntryPriv; + +class JSCallHistoryEntry +{ +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, + const Api::Call::CallHistoryEntryProperties &callEntry); + +private: + static void initialize(JSContextRef context, + JSObjectRef object); + + static void finalize(JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception); + + static JSClassDefinition m_classInfo; + + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; +} +} + +#endif + diff --git a/src/standards/Tizen/Call/ResponseDispatcher.cpp b/src/standards/Tizen/Call/ResponseDispatcher.cpp new file mode 100755 index 0000000..60fef9f --- /dev/null +++ b/src/standards/Tizen/Call/ResponseDispatcher.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "ResponseDispatcher.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include "JSCallHistory.h" +#include "Converter.h" + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { +ResponseDispatcher& ResponseDispatcher::getInstance() +{ + static ResponseDispatcher dispatcher; + return dispatcher; +} + +ResponseDispatcher::ResponseDispatcher() : + EventAnswerReceiver(ThreadEnum::NULL_THREAD), + EventAnswerReceiver(ThreadEnum::NULL_THREAD) +{ +} + +void ResponseDispatcher::OnAnswerReceived(const Api::Call::EventFindCallHistoryPtr& event) +{ + DPL::SharedPtr data = DPL::DynamicPointerCast(event->getPrivateData()); + Assert(NULL != data); + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + Converter converter(data->getContext()); + try { + data->callOnSuccess(converter.toJSValueRef(event->getResult(), data->getContext())); + } catch(WrtDeviceApis::Commons::ConversionException) { + data->callOnError(JSTizenExceptionFactory::makeErrorObject(data->getContext(), JSTizenException::IO_ERROR, "IO error")); + } + } else { + JSObjectRef jsException = NULL; + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::SecurityException) { + jsException = JSTizenExceptionFactory::makeErrorObject(data->getContext(), JSTizenException::PERMISSION_DENIED_ERROR, "Permission denied error"); + } else { + jsException = JSTizenExceptionFactory::makeErrorObject(data->getContext(), JSTizenException::IO_ERROR, "IO error"); + } + data->callOnError(jsException); + } +} + +void ResponseDispatcher::OnAnswerReceived(const Api::Call::EventRemoveBatchPtr& event) +{ + DPL::SharedPtr data = DPL::DynamicPointerCast(event->getPrivateData()); + Assert(NULL != data); + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + Try { + data->callOnSuccess(); + } Catch(WrtDeviceApis::Commons::ConversionException) { + data->callOnError(JSTizenExceptionFactory::makeErrorObject(data->getContext(), JSTizenException::IO_ERROR, "IO error")); + } + } else { + JSObjectRef jsException = NULL; + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::SecurityException) { + jsException = JSTizenExceptionFactory::makeErrorObject(data->getContext(), JSTizenException::PERMISSION_DENIED_ERROR, "Permission denied error"); + } else { + jsException = JSTizenExceptionFactory::makeErrorObject(data->getContext(), JSTizenException::IO_ERROR, "IO error"); + } + data->callOnError(jsException); + } +} + +} +} + diff --git a/src/standards/Tizen/Call/ResponseDispatcher.h b/src/standards/Tizen/Call/ResponseDispatcher.h new file mode 100755 index 0000000..24a39c5 --- /dev/null +++ b/src/standards/Tizen/Call/ResponseDispatcher.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef TIZENAPIS_TIZEN_CALL_RESPONSEDISPATCHER_H_ +#define TIZENAPIS_TIZEN_CALL_RESPONSEDISPATCHER_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +class ResponseDispatcher : + public WrtDeviceApis::Commons::EventAnswerReceiver, + public WrtDeviceApis::Commons::EventAnswerReceiver +{ +public: + static ResponseDispatcher& getInstance(); + + void OnAnswerReceived(const Api::Call::EventFindCallHistoryPtr& event); + void OnAnswerReceived(const Api::Call::EventRemoveBatchPtr& event); + +protected: + ResponseDispatcher(); +}; +} +} + +#endif + diff --git a/src/standards/Tizen/Call/config.xml b/src/standards/Tizen/Call/config.xml new file mode 100755 index 0000000..6f0a7b7 --- /dev/null +++ b/src/standards/Tizen/Call/config.xml @@ -0,0 +1,32 @@ + + + + libwrt-plugins-tizen-1.0-call.so + call.install.uri + SAMSUNG plugin group + SAMSUNG certificate authority + AAAABBBBCCCCDDDEEEE0000 + + + http://tizen.org/api/call + call + + + + http://tizen.org/api/call.history + call.history.read + call.history.write + + + + http://tizen.org/api/call.history.read + call.history.read + + + + http://tizen.org/api/call.history.write + call.history.read + call.history.write + + + diff --git a/src/standards/Tizen/Call/plugin_config.cpp b/src/standards/Tizen/Call/plugin_config.cpp new file mode 100755 index 0000000..e51423e --- /dev/null +++ b/src/standards/Tizen/Call/plugin_config.cpp @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include + +#include +#include +#include +#include + +#define CALL_FEATURE_API "http://tizen.org/api/call" +#define CALL_HISTORY_FEATURE_API "http://tizen.org/api/call.history" +#define CALL_HISTORY_FEATURE_API_READ "http://tizen.org/api/call.history.read" +#define CALL_HISTORY_FEATURE_API_WRITE "http://tizen.org/api/call.history.write" + +namespace TizenApis { +namespace Tizen1_0 { + +const char* CALL_HISTORY_DEVICE_CAP_READ = "call.history.read"; +const char* CALL_HISTORY_DEVICE_CAP_WRITE = "call.history.write"; + +const char* CALL_HISTORY_FUNCTION_API_FIND = "find"; +const char* CALL_HISTORY_FUNCTION_API_REMOVE = "remove"; +const char* CALL_HISTORY_FUNCTION_API_REMOVE_BATCH = "removeBatch"; + +static WrtDeviceApis::Commons::FunctionMapping createCallFunctions(); + +static WrtDeviceApis::Commons::FunctionMapping CallFunctions = createCallFunctions(); + +DEFINE_FUNCTION_GETTER(Call, CallFunctions); + +static WrtDeviceApis::Commons::FunctionMapping createCallFunctions() +{ + using namespace WrtDeviceApis::Commons; + + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_CALL_HISTORY_READ, CALL_HISTORY_DEVICE_CAP_READ); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_CALL_HISTORY_WRITE, CALL_HISTORY_DEVICE_CAP_WRITE); + + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_CALL_HISTORY_READ); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_CALL_HISTORY_READ, DEVICE_CAP_CALL_HISTORY_READ); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_CALL_HISTORY_WRITE); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_CALL_HISTORY_WRITE, DEVICE_CAP_CALL_HISTORY_WRITE); + + ACE_CREATE_FEATURE(FEATURE_CALL, CALL_FEATURE_API); + ACE_CREATE_FEATURE(FEATURE_CALL_HISTORY, CALL_HISTORY_FEATURE_API); + ACE_CREATE_FEATURE(FEATURE_CALL_HISTORY_READ, CALL_HISTORY_FEATURE_API_READ); + ACE_CREATE_FEATURE(FEATURE_CALL_HISTORY_WRITE, CALL_HISTORY_FEATURE_API_WRITE); + + ACE_CREATE_FEATURE_LIST(CALL_FEATURES_CALL_HISTORY_READ_WRITE); + ACE_ADD_API_FEATURE(CALL_FEATURES_CALL_HISTORY_READ_WRITE, FEATURE_CALL); + ACE_ADD_API_FEATURE(CALL_FEATURES_CALL_HISTORY_READ_WRITE, FEATURE_CALL_HISTORY); + ACE_ADD_API_FEATURE(CALL_FEATURES_CALL_HISTORY_READ_WRITE, FEATURE_CALL_HISTORY_READ); + ACE_ADD_API_FEATURE(CALL_FEATURES_CALL_HISTORY_READ_WRITE, FEATURE_CALL_HISTORY_WRITE); + + ACE_CREATE_FEATURE_LIST(CALL_FEATURES_CALL_HISTORY_READ); + ACE_ADD_API_FEATURE(CALL_FEATURES_CALL_HISTORY_READ, FEATURE_CALL); + ACE_ADD_API_FEATURE(CALL_FEATURES_CALL_HISTORY_READ, FEATURE_CALL_HISTORY); + ACE_ADD_API_FEATURE(CALL_FEATURES_CALL_HISTORY_READ, FEATURE_CALL_HISTORY_READ); + + ACE_CREATE_FEATURE_LIST(CALL_FEATURES_CALL_HISTORY_WRITE); + ACE_ADD_API_FEATURE(CALL_FEATURES_CALL_HISTORY_WRITE, FEATURE_CALL); + ACE_ADD_API_FEATURE(CALL_FEATURES_CALL_HISTORY_WRITE, FEATURE_CALL_HISTORY); + ACE_ADD_API_FEATURE(CALL_FEATURES_CALL_HISTORY_WRITE, FEATURE_CALL_HISTORY_WRITE); + + FunctionMapping CallMapping; + + AceFunction findFunc = ACE_CREATE_FUNCTION( + FUNCTION_FIND, + CALL_HISTORY_FUNCTION_API_FIND, + CALL_FEATURES_CALL_HISTORY_READ_WRITE, + EMPTY_DEVICE_LIST); + + CallMapping.insert(std::make_pair(CALL_HISTORY_FUNCTION_API_FIND, findFunc)); + + AceFunction removeFunc = ACE_CREATE_FUNCTION( + FUNCTION_REMOVE, + CALL_HISTORY_FUNCTION_API_REMOVE, + CALL_FEATURES_CALL_HISTORY_WRITE, + EMPTY_DEVICE_LIST); + + CallMapping.insert(std::make_pair(CALL_HISTORY_FUNCTION_API_REMOVE, removeFunc)); + + AceFunction removeBatchFunc = ACE_CREATE_FUNCTION( + FUNCTION_REMOVE_BATCH, + CALL_HISTORY_FUNCTION_API_REMOVE_BATCH, + CALL_FEATURES_CALL_HISTORY_WRITE, + EMPTY_DEVICE_LIST); + + CallMapping.insert(std::make_pair(CALL_HISTORY_FUNCTION_API_REMOVE_BATCH, removeBatchFunc)); + + return CallMapping; +} + +} +} diff --git a/src/standards/Tizen/Call/plugin_config.h b/src/standards/Tizen/Call/plugin_config.h new file mode 100755 index 0000000..03de843 --- /dev/null +++ b/src/standards/Tizen/Call/plugin_config.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _CALL_PLUGIN_CONFIG_H_ +#define _CALL_PLUGIN_CONFIG_H_ + +#include + +namespace TizenApis { +namespace Tizen1_0 { + +extern const char* CALL_HISTORY_FUNCTION_API_FIND; +extern const char* CALL_HISTORY_FUNCTION_API_REMOVE; +extern const char* CALL_HISTORY_FUNCTION_API_REMOVE_BATCH; + +DECLARE_FUNCTION_GETTER(Call); + +} +} + +namespace WrtDeviceApis { +namespace Commons { + +#define CALL_HISTORY_CHECK_ACCESS(globalContext, functionName) \ + WrtDeviceApis::Commons::aceCheckAccess >( \ + globalContext, \ + getCallFunctionData, \ + functionName) +} +} + +#endif diff --git a/src/standards/Tizen/Call/plugin_initializer.cpp b/src/standards/Tizen/Call/plugin_initializer.cpp new file mode 100755 index 0000000..ef042a6 --- /dev/null +++ b/src/standards/Tizen/Call/plugin_initializer.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include "JSCallApi.h" + +#define CALL "call" + +using namespace WrtDeviceApis::Commons; + +void on_widget_start_callback(int widgetId, JavaScriptContext context, const engine_interface_t *interface) { + Try { + WrtDeviceApis::Commons::WrtWrappersMgr::getInstance().registerWrapper(widgetId,context,interface); + } Catch(Exception) { + LogError("Wrt wrapper registration failed"); + } +} + +void on_widget_stop_callback(int widgetId) { + WrtDeviceApis::Commons::WrtWrappersMgr::getInstance().removeWrapper(widgetId); +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) + +PLUGIN_CLASS_MAP_BEGIN + PLUGIN_CLASS_MAP_ADD_CLASS( + WRT_JS_EXTENSION_OBJECT_TIZEN, + CALL, + TizenApis::Tizen1_0::JSCallApi::getClassRef(), + NULL) +PLUGIN_CLASS_MAP_END + diff --git a/src/standards/Tizen/Common/JSTizenException.cpp b/src/standards/Tizen/Common/JSTizenException.cpp new file mode 100644 index 0000000..90502fd --- /dev/null +++ b/src/standards/Tizen/Common/JSTizenException.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "JSTizenException.h" + +#include + +#include + +namespace TizenApis { + namespace Commons { + + const std::string JSTizenException::UNKNOWN_ERROR = "UNKNOWN_ERROR"; + const std::string JSTizenException::TYPE_MISMATCH_ERROR = "TYPE_MISMATCH_ERROR"; + const std::string JSTizenException::INVALID_VALUES_ERROR = "INVALID_VALUES_ERROR"; + const std::string JSTizenException::TIMEOUT_ERROR = "TIMEOUT_ERROR"; + const std::string JSTizenException::IO_ERROR = "IO_ERROR"; + const std::string JSTizenException::NOT_SUPPORTED_ERROR = "NOT_SUPPORTED_ERROR"; + const std::string JSTizenException::PERMISSION_DENIED_ERROR = "PERMISSION_DENIED_ERROR"; + const std::string JSTizenException::NOT_FOUND_ERROR = "NOT_FOUND_ERROR"; + + namespace{ + #define PLUGIN_NAME "TizenException" + #define PROPERTY_NAME "name" + #define PROPERTY_MESSAGE "message" + + const std::string PROPERTY_ERROR[] = { + TizenApis::Commons::JSTizenException::UNKNOWN_ERROR, + TizenApis::Commons::JSTizenException::TYPE_MISMATCH_ERROR, + TizenApis::Commons::JSTizenException::INVALID_VALUES_ERROR, + TizenApis::Commons::JSTizenException::TIMEOUT_ERROR, + TizenApis::Commons::JSTizenException::IO_ERROR, + TizenApis::Commons::JSTizenException::NOT_SUPPORTED_ERROR, + TizenApis::Commons::JSTizenException::PERMISSION_DENIED_ERROR, + TizenApis::Commons::JSTizenException::NOT_FOUND_ERROR, + }; + } + + JSClassRef JSTizenException::m_classRef = NULL; + + JSClassDefinition JSTizenException::m_classInfo = { + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + m_properties, + NULL, //__function, + initialize, + finalize, + hasProperty, + NULL, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, + NULL, //ConvertToType, + }; + + JSStaticValue JSTizenException::m_properties[] = { + { PROPERTY_NAME, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_MESSAGE, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } + }; + + const JSClassDefinition* JSTizenException::getClassInfo() { + return &m_classInfo; + } + + JSClassRef JSTizenException::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; + } + + void JSTizenException::initialize(JSContextRef /*context*/, JSObjectRef /*object*/) { + } + + void JSTizenException::finalize(JSObjectRef object) { + PrivateObject* privateObject = static_cast (JSObjectGetPrivate(object)); + if (privateObject) { + JSObjectSetPrivate(object, NULL); + delete privateObject; + } + } + + bool JSTizenException::hasProperty(JSContextRef /*context*/, JSObjectRef /*object*/, JSStringRef propertyName) { + const size_t size = sizeof(PROPERTY_ERROR) / sizeof(PROPERTY_ERROR[0]); + for (size_t i = 0; i < size; ++i) { + if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_ERROR[i].c_str())) { + return true; + } + } + return false; + } + + JSValueRef JSTizenException::getStaticProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* /*exception*/) { + PrivateObject* privateObject = static_cast (JSObjectGetPrivate(object)); + if (!privateObject) { + LogError("Private object is not set."); + return JSValueMakeUndefined(context); + } + + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + try { + if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_NAME)) { + return converter.toJSValueRef(privateObject->getObject()->getName()); + } else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_MESSAGE)) { + return converter.toJSValueRef(privateObject->getObject()->getMessage()); + } + } catch (const WrtDeviceApis::Commons::ConversionException& ex) { + LogError("Exception: " << ex.GetMessage()); + } + + return JSValueMakeUndefined(context); + } + + bool JSTizenException::hasInstance(JSContextRef context, JSObjectRef /*constructor*/, JSValueRef possibleInstance, JSValueRef* /*exception*/) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); + } + + }// Commons +} //TizenApis diff --git a/src/standards/Tizen/Common/JSTizenException.h b/src/standards/Tizen/Common/JSTizenException.h new file mode 100644 index 0000000..af0e248 --- /dev/null +++ b/src/standards/Tizen/Common/JSTizenException.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef JSTIZENEXCEPTION_H_ +#define JSTIZENEXCEPTION_H_ + +#include +#include + +#include "TizenExceptionData.h" + +namespace TizenApis { + + namespace Commons { + + class JSTizenException { + public: + typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type PrivateObject; + + public: + static const std::string UNKNOWN_ERROR; + static const std::string TYPE_MISMATCH_ERROR; + static const std::string INVALID_VALUES_ERROR; + static const std::string TIMEOUT_ERROR; + static const std::string IO_ERROR; + static const std::string NOT_SUPPORTED_ERROR; + static const std::string PERMISSION_DENIED_ERROR; + static const std::string NOT_FOUND_ERROR; + + public: + static JSClassRef getClassRef(); + + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getStaticProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_properties[]; + + static JSClassRef m_classRef; + }; + + } + +} + +#endif /* JSTIZENEXCEPTION_H_ */ diff --git a/src/standards/Tizen/Common/JSTizenExceptionFactory.cpp b/src/standards/Tizen/Common/JSTizenExceptionFactory.cpp new file mode 100644 index 0000000..58e91bc --- /dev/null +++ b/src/standards/Tizen/Common/JSTizenExceptionFactory.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "JSTizenExceptionFactory.h" + +#include +#include + +#include + +#include "TizenExceptionData.h" +#include "JSTizenException.h" + +namespace TizenApis { + + namespace Commons { + JSTizenExceptionFactory::JSTizenExceptionFactory() { + } + + JSTizenExceptionFactory::~JSTizenExceptionFactory() { + } + + JSObjectRef JSTizenExceptionFactory::makeErrorObject(JSContextRef context, const std::string& name, const std::string& message) { + JSTizenException::PrivateObject::ObjectType data(new TizenExceptionData(name, message)); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(context, JSTizenException::getClassRef(), data); + } + + JSValueRef JSTizenExceptionFactory::postException(JSContextRef context, JSValueRef* exception, const std::string& name, const std::string& message) { + Assert(exception && "Exception object can't be NULL."); + JSTizenException::PrivateObject::ObjectType data(new TizenExceptionData(name, message)); + *exception = WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(context, JSTizenException::getClassRef(), data); + return JSValueMakeUndefined(context); + } + + } // Commons + +} //TizenApis diff --git a/src/standards/Tizen/Common/JSTizenExceptionFactory.h b/src/standards/Tizen/Common/JSTizenExceptionFactory.h new file mode 100644 index 0000000..d7dc1a4 --- /dev/null +++ b/src/standards/Tizen/Common/JSTizenExceptionFactory.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef JSTIZENEXCEPTIONFACTORY_H_ +#define JSTIZENEXCEPTIONFACTORY_H_ + + +#include +#include +#include + +namespace TizenApis { + + namespace Commons { + + class JSTizenExceptionFactory : public DPL::Noncopyable { + public: + JSTizenExceptionFactory(); + virtual ~JSTizenExceptionFactory(); + + public: + static JSObjectRef makeErrorObject(JSContextRef context, const std::string& name, const std::string& message=std::string()); + static JSValueRef postException (JSContextRef context, JSValueRef* exception, const std::string& name, const std::string& message=std::string()); + }; + + } //Commons + +} //TizenApis + +#endif /* JSTIZENEXCEPTIONFACTORY_H_ */ diff --git a/src/standards/Tizen/Common/SecurityExceptions.h b/src/standards/Tizen/Common/SecurityExceptions.h new file mode 100755 index 0000000..a82bc00 --- /dev/null +++ b/src/standards/Tizen/Common/SecurityExceptions.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENAPIS_COMMONS_JS_SECURITYEXCEPTIONS_H_ +#define TIZENAPIS_COMMONS_JS_SECURITYEXCEPTIONS_H_ + +#include +#include "JSTizenExceptionFactory.h" + +namespace TizenApis { +namespace Commons { + +/** + * synchronously checks access status and throws JS Security exception if + * necessary + */ + #define TIZEN_SYNC_ACCESS_HANDLER(status, context, exception) \ + do { \ + switch (status) { \ + case AceSecurityStatus::InternalError: \ + return JSTizenExceptionFactory::postException(context, exception, \ + JSTizenException::UNKNOWN_ERROR); \ + break; \ + case AceSecurityStatus::AccessDenied: \ + return JSTizenExceptionFactory::postException(context, exception, \ + JSTizenException::PERMISSION_DENIED_ERROR); \ + break; \ + default: \ + break; \ + } \ + } while (0) + +/** + * checks access status and returns an error through JSCallbackManager if + * necessary + */ +#define TIZEN_ASYNC_CBM_ACCESS_HANDLER(status, context, cbm) \ + do { \ + switch (status) { \ + case AceSecurityStatus::InternalError: \ + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, \ + "SECURITY_ERROR", "internal error")); \ + return JSValueMakeNull(context); \ + case AceSecurityStatus::AccessDenied: \ + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, \ + JSTizenException::PERMISSION_DENIED_ERROR, "PERMISSION_DENIED_ERROR")); \ + return JSValueMakeNull(context); \ + default: \ + break; \ + } \ + } while (0) + +} +} +#endif /*TIZENAPIS_COMMONS_JS_SECURITYEXCEPTIONS_H_ */ + diff --git a/src/standards/Tizen/Common/TizenExceptionData.cpp b/src/standards/Tizen/Common/TizenExceptionData.cpp new file mode 100644 index 0000000..12a3076 --- /dev/null +++ b/src/standards/Tizen/Common/TizenExceptionData.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "TizenExceptionData.h" +namespace TizenApis { + namespace Commons { + + TizenExceptionData::TizenExceptionData(const std::string& name, const std::string& message) : + m_name(name), m_message(message) { + } + + TizenExceptionData::~TizenExceptionData() { + } + + std::string TizenExceptionData::getName() const { + return m_name; + } + + std::string TizenExceptionData::getMessage() const { + return m_message; + } + + } // Commons +} // TizenApis diff --git a/src/standards/Tizen/Common/TizenExceptionData.h b/src/standards/Tizen/Common/TizenExceptionData.h new file mode 100644 index 0000000..5cd3b33 --- /dev/null +++ b/src/standards/Tizen/Common/TizenExceptionData.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIZENEXCEPTIONDATA_H_ +#define TIZENEXCEPTIONDATA_H_ + +#include +#include + +namespace TizenApis { +namespace Commons { + +class TizenExceptionData { + public: + TizenExceptionData(const std::string& name, const std::string& message = std::string()); + virtual ~TizenExceptionData(); + + std::string getName() const; + std::string getMessage() const; + + private : + std::string m_name; + std::string m_message; +}; + +typedef DPL::SharedPtr TizenExceptionDataPtr; + +} // Commons +} // TizenApis + +#endif /* TIZENEXCEPTIONDATA_H_ */ diff --git a/src/standards/Tizen/Contact/AddressBookController.cpp b/src/standards/Tizen/Contact/AddressBookController.cpp new file mode 100755 index 0000000..7d1a963 --- /dev/null +++ b/src/standards/Tizen/Contact/AddressBookController.cpp @@ -0,0 +1,459 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactManagerController.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include "AddressBookController.h" +#include "ContactConverter.h" +#include "JSAddressBookChangeCallbackManager.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +AddressBookController::AddressBookController(JSContextRef context, IAddressBookPtr addressBook) : + EventAddressBookAddBatchEventAnswerReceiver(ThreadEnum::NULL_THREAD), + EventAddressBookUpdateBatchEventAnswerReceiver(ThreadEnum::NULL_THREAD), + EventAddressBookRemoveBatchEventAnswerReceiver(ThreadEnum::NULL_THREAD), + EventAddressBookFindEventAnswerReceiver(ThreadEnum::NULL_THREAD), + EventAddressBookChangeListenerListener(ThreadEnum::NULL_THREAD), + AddressBookPrivObject(context, addressBook) +{ + if (!addressBook) { + LogWarning("controller has no addressBook object"); + } +} + +AddressBookController::~AddressBookController() +{ +} + +void AddressBookAsyncAnswerHandler::addBatch(const EventAddressBookAddBatchPtr &event) +{ + JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast(event->getPrivateData()); + if (!callbackManager) { + LogError("no callback manager"); + return; + } + + JSContextRef gContext = callbackManager->getContext(); + + JSValueRef error = NULL; + if (ExceptionCodes::None != event->getExceptionCode()) + { + switch (event->getExceptionCode()) + { + case ExceptionCodes::PlatformException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Internal error"); + break; + case ExceptionCodes::InvalidArgumentException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::TYPE_MISMATCH_ERROR, "Invalid value error"); + break; + case ExceptionCodes::ConversionException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong argument"); + break; + default: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Unknown error"); + break; + } + + callbackManager->callOnError(error); + return; + } + + Try { + if (!event->getResult()) + ThrowMsg(PlatformException, "No result."); + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(gContext); + ContactArrayPtr contacts = event->getContacts(); + + JSValueRef result = converter->toJSValueRef(contacts); + + callbackManager->callOnSuccess(result); + return; + } Catch(Exception) { + LogError("error during processing answer" << _rethrown_exception.GetMessage()); + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Internal error"); + + callbackManager->callOnError(error); + return; + } +} + +void AddressBookAsyncAnswerHandler::updateBatch(const EventAddressBookUpdateBatchPtr &event) +{ + JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast(event->getPrivateData()); + if (!callbackManager) { + LogError("no callback manager"); + return; + } + + JSContextRef gContext = callbackManager->getContext(); + + JSValueRef error = NULL; + if (ExceptionCodes::None != event->getExceptionCode()) + { + switch (event->getExceptionCode()) + { + case ExceptionCodes::PlatformException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Internal error"); + break; + case ExceptionCodes::NotFoundException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::NOT_FOUND_ERROR, "record not found"); + break; + case ExceptionCodes::InvalidArgumentException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::TYPE_MISMATCH_ERROR, "Invalid value error"); + break; + case ExceptionCodes::ConversionException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong argument"); + break; + default: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Unknown error"); + break; + } + + callbackManager->callOnError(error); + return; + } + + callbackManager->callOnSuccess(); +} + +void AddressBookAsyncAnswerHandler::removeBatch(const EventAddressBookRemoveBatchPtr &event) +{ + JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast(event->getPrivateData()); + if (!callbackManager) { + LogError("no callback manager"); + return; + } + + JSContextRef gContext = callbackManager->getContext(); + + JSValueRef error = NULL; + if (ExceptionCodes::None != event->getExceptionCode()) + { + switch (event->getExceptionCode()) + { + case ExceptionCodes::PlatformException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Internal error"); + break; + case ExceptionCodes::NotFoundException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::NOT_FOUND_ERROR, "record not found"); + break; + case ExceptionCodes::InvalidArgumentException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::TYPE_MISMATCH_ERROR, "Invalid value error"); + break; + case ExceptionCodes::ConversionException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong argument"); + break; + default: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Unknown error"); + break; + } + callbackManager->callOnError(error); + return; + } + + callbackManager->callOnSuccess(); +} + +void AddressBookAsyncAnswerHandler::find(const EventAddressBookFindPtr &event) +{ + JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast(event->getPrivateData()); + if (!callbackManager) + { + LogError("no callback manager"); + return; + } + + JSContextRef gContext = callbackManager->getContext(); + + JSValueRef error = NULL; + if (ExceptionCodes::None != event->getExceptionCode()) + { + switch (event->getExceptionCode()) + { + case ExceptionCodes::PlatformException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::NOT_SUPPORTED_ERROR, "Not support such a filter"); + break; + case ExceptionCodes::InvalidArgumentException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::TYPE_MISMATCH_ERROR, "Invalid value error"); + break; + case ExceptionCodes::ConversionException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong argument"); + break; + default: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Unknown error"); + break; + } + + callbackManager->callOnError(error); + return; + } + + Try { + if (!event->getResult()) + ThrowMsg(PlatformException, "No result."); + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(gContext); + ContactArrayPtr contacts = event->getContacts(); + + JSValueRef result = converter->toJSValueRef(contacts); + + callbackManager->callOnSuccess(result); + return; + } Catch(Exception) { + LogError("error during processing answer" << _rethrown_exception.GetMessage()); + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Internal error"); + + callbackManager->callOnError(error); + return; + } +} + +void AddressBookAsyncAnswerHandler::changeListenerError(const EventAddressBookChangeListenerPtr &event) +{ + JSValueRef errorObject; + + JSCallbackManagerPtr cbm = DPL::StaticPointerCast(event->getPrivateData()); + if (!cbm) + { + LogError("no callback manager"); + return; + } + + JSContextRef gContext = cbm->getContext(); + + if (event->getExceptionCode() == ExceptionCodes::NotFoundException) + errorObject = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::NOT_FOUND_ERROR, "Not found error"); + else + errorObject = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Unknown error"); + + cbm->callOnError(errorObject); +} + +void AddressBookAsyncAnswerHandler::changeListenerContactAdded(const EventAddressBookChangeListenerPtr &event) +{ + JSAddressBookChangeCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + if (!cbm) + { + LogError("no callback manager"); + return; + } + + EventInfoAddressBookChangePtr _eventInfo = event->getEventInfo(); + if(_eventInfo->getCallbackType() != EventInfoAddressBookChange::OnContactsAdded) + { + LogError("wrong type"); + return; + } + + EventInfoAddressBookChangeAddedPtr eventInfo = DPL::DynamicPointerCast(_eventInfo); + + if (!eventInfo->getContactsIsSet()) + { + LogError("no data set"); + return; + } + + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(cbm->getContext()); + + JSValueRef contacts; + Try { + contacts = converter->toJSValueRef(eventInfo->getContacts()); + } Catch (Exception) { + LogError("Conversion error"); + return; + } + + cbm->callOnContactsAdded(contacts); +} + +void AddressBookAsyncAnswerHandler::changeListenerContactUpdated(const EventAddressBookChangeListenerPtr &event) +{ + JSAddressBookChangeCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + if (!cbm) + { + LogError("no callback manager"); + return; + } + + EventInfoAddressBookChangePtr _eventInfo = event->getEventInfo(); + if(_eventInfo->getCallbackType() != EventInfoAddressBookChange::OnContactsUpdated) + { + LogError("wrong type"); + return; + } + + EventInfoAddressBookChangeUpdatedPtr eventInfo = DPL::DynamicPointerCast(_eventInfo); + + if (!eventInfo->getContactsIsSet()) + { + LogError("no data set"); + return; + } + + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(cbm->getContext()); + + JSValueRef contacts; + Try { + contacts = converter->toJSValueRef(eventInfo->getContacts()); + } Catch (Exception) { + LogError("Conversion error"); + return; + } + + cbm->callOnContactsUpdated(contacts); +} + +void AddressBookAsyncAnswerHandler::changeListenerContactRemoved(const EventAddressBookChangeListenerPtr &event) +{ + JSAddressBookChangeCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + if (!cbm) + { + LogError("no callback manager"); + return; + } + + EventInfoAddressBookChangePtr _eventInfo = event->getEventInfo(); + if(_eventInfo->getCallbackType() != EventInfoAddressBookChange::OnContactsRemoved) + { + LogError("wrong type"); + return; + } + + EventInfoAddressBookChangeRemovedPtr eventInfo = DPL::DynamicPointerCast(_eventInfo); + if (!eventInfo->getContactIdsIsSet()) + { + LogError("no data set"); + return; + } + + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(cbm->getContext()); + + JSValueRef contactIds; + Try { + contactIds = converter->toJSValueRef(eventInfo->getContactIds()); + } Catch (Exception) { + LogError("Conversion error"); + return; + } + + cbm->callOnContactsAdded(contactIds); +} + +void AddressBookAsyncAnswerHandler::changeListenerAddressBookReset(const EventAddressBookChangeListenerPtr &event) +{ + JSAddressBookChangeCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + if (!cbm) + { + LogError("no callback manager"); + return; + } + + cbm->callOnAddressBookReset(); +} + +void AddressBookController::OnAnswerReceived(const EventAddressBookAddBatchPtr &event) +{ + AddressBookAsyncAnswerHandler::addBatch(event); +} + +void AddressBookController::OnAnswerReceived(const EventAddressBookUpdateBatchPtr &event) +{ + AddressBookAsyncAnswerHandler::updateBatch(event); +} + +void AddressBookController::OnAnswerReceived(const EventAddressBookRemoveBatchPtr &event) +{ + AddressBookAsyncAnswerHandler::removeBatch(event); +} + +void AddressBookController::OnAnswerReceived(const EventAddressBookFindPtr &event) +{ + AddressBookAsyncAnswerHandler::find(event); +} + +void AddressBookController::onAnswerReceived(const EventAddressBookChangeListenerPtr &event) +{ + EventInfoAddressBookChangePtr eventInfo = event->getEventInfo(); + if(eventInfo == NULL) + { + LogError("wrong type"); + return; + } + + EventInfoAddressBookChange::CallbackType type = eventInfo->getCallbackType(); + if(type == EventInfoAddressBookChange::OnContactsAdded) + AddressBookAsyncAnswerHandler::changeListenerContactAdded(event); + else if(type == EventInfoAddressBookChange::OnContactsUpdated) + AddressBookAsyncAnswerHandler::changeListenerContactUpdated(event); + else if(type == EventInfoAddressBookChange::OnContactsRemoved) + AddressBookAsyncAnswerHandler::changeListenerContactRemoved(event); + else if(type == EventInfoAddressBookChange::OnAddressBookReset) + AddressBookAsyncAnswerHandler::changeListenerAddressBookReset(event); + else if(type == EventInfoAddressBookChange::OnError) + AddressBookAsyncAnswerHandler::changeListenerError(event); +} + +void AddressBookAddBatchPendingOperation::handleCallingCallbacks() +{ + AddressBookAsyncAnswerHandler::addBatch(DPL::StaticPointerCast(m_event)); +} + +void AddressBookUpdateBatchPendingOperation::handleCallingCallbacks() +{ + AddressBookAsyncAnswerHandler::updateBatch(DPL::StaticPointerCast(m_event)); +} + +void AddressBookRemoveBatchPendingOperation::handleCallingCallbacks() +{ + AddressBookAsyncAnswerHandler::removeBatch(DPL::StaticPointerCast(m_event)); +} + +void AddressBookFindPendingOperation::handleCallingCallbacks() +{ + AddressBookAsyncAnswerHandler::find(DPL::StaticPointerCast(m_event)); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/AddressBookController.h b/src/standards/Tizen/Contact/AddressBookController.h new file mode 100755 index 0000000..7e027c2 --- /dev/null +++ b/src/standards/Tizen/Contact/AddressBookController.h @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file AddressBookController.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_ADDRESS_BOOK_CONTROLLER_H_ +#define _TIZEN_CONTACT_ADDRESS_BOOK_CONTROLLER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject AddressBookPrivObject; + +typedef WrtDeviceApis::Commons::EventAnswerReceiver EventAddressBookAddBatchEventAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver EventAddressBookUpdateBatchEventAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver EventAddressBookRemoveBatchEventAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver EventAddressBookFindEventAnswerReceiver; +typedef WrtDeviceApis::Commons::EventListener EventAddressBookChangeListenerListener; + +class AddressBookController : + public EventAddressBookAddBatchEventAnswerReceiver, + public EventAddressBookUpdateBatchEventAnswerReceiver, + public EventAddressBookRemoveBatchEventAnswerReceiver, + public EventAddressBookFindEventAnswerReceiver, + public EventAddressBookChangeListenerListener, + public AddressBookPrivObject +{ +public: + AddressBookController(JSContextRef context, + TizenApis::Api::Contact::IAddressBookPtr addressBook); + virtual ~AddressBookController(); +protected: + void OnAnswerReceived(const TizenApis::Api::Contact::EventAddressBookAddBatchPtr &event); + void OnAnswerReceived(const TizenApis::Api::Contact::EventAddressBookUpdateBatchPtr &event); + void OnAnswerReceived(const TizenApis::Api::Contact::EventAddressBookRemoveBatchPtr &event); + void OnAnswerReceived(const TizenApis::Api::Contact::EventAddressBookFindPtr &event); + void onAnswerReceived(const TizenApis::Api::Contact::EventAddressBookChangeListenerPtr &event); +}; + +typedef DPL::SharedPtr AddressBookControllerPtr; + +// Pending operation objects +class AddressBookAddBatchPendingOperation : public WrtDeviceApis::CommonsJavaScript::IJSPendingOperationPrivateObject +{ +public: + AddressBookAddBatchPendingOperation( + DPL::SharedPtr &event) : + WrtDeviceApis::CommonsJavaScript::IJSPendingOperationPrivateObject(event) + { + } + virtual void handleCallingCallbacks(); +}; + +class AddressBookUpdateBatchPendingOperation : public WrtDeviceApis::CommonsJavaScript::IJSPendingOperationPrivateObject +{ + public: + AddressBookUpdateBatchPendingOperation( + DPL::SharedPtr &event) : + WrtDeviceApis::CommonsJavaScript::IJSPendingOperationPrivateObject(event) + { + } + virtual void handleCallingCallbacks(); +}; + +class AddressBookRemoveBatchPendingOperation : public WrtDeviceApis::CommonsJavaScript::IJSPendingOperationPrivateObject +{ + public: + AddressBookRemoveBatchPendingOperation( + DPL::SharedPtr &event) : + WrtDeviceApis::CommonsJavaScript::IJSPendingOperationPrivateObject(event) + { + } + virtual void handleCallingCallbacks(); +}; + +class AddressBookFindPendingOperation : public WrtDeviceApis::CommonsJavaScript::IJSPendingOperationPrivateObject +{ + public: + AddressBookFindPendingOperation( + DPL::SharedPtr &event) : + WrtDeviceApis::CommonsJavaScript::IJSPendingOperationPrivateObject(event) + { + } + virtual void handleCallingCallbacks(); +}; + +//common part +class AddressBookAsyncAnswerHandler +{ +public: + static void addBatch(const TizenApis::Api::Contact::EventAddressBookAddBatchPtr &event); + static void updateBatch(const TizenApis::Api::Contact::EventAddressBookUpdateBatchPtr &event); + static void removeBatch(const TizenApis::Api::Contact::EventAddressBookRemoveBatchPtr &event); + static void find(const TizenApis::Api::Contact::EventAddressBookFindPtr &event); + static void changeListenerError(const TizenApis::Api::Contact::EventAddressBookChangeListenerPtr &event); + static void changeListenerContactAdded(const TizenApis::Api::Contact::EventAddressBookChangeListenerPtr &event); + static void changeListenerContactUpdated(const TizenApis::Api::Contact::EventAddressBookChangeListenerPtr &event); + static void changeListenerContactRemoved(const TizenApis::Api::Contact::EventAddressBookChangeListenerPtr &event); + static void changeListenerAddressBookReset(const TizenApis::Api::Contact::EventAddressBookChangeListenerPtr &event); +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_ADDRESS_BOOK_CONTROLLER_H_ diff --git a/src/standards/Tizen/Contact/CMakeLists.txt b/src/standards/Tizen/Contact/CMakeLists.txt new file mode 100755 index 0000000..b809943 --- /dev/null +++ b/src/standards/Tizen/Contact/CMakeLists.txt @@ -0,0 +1,55 @@ +set(TARGET_NAME "wrt-plugins-tizen-1.0-contact") +set(DESTINATION_NAME "tizen-1.0-contact") +set(SRCS + ${SRCS_PLATFORM_API_CONTACT} + ${SRCS_PLATFORM_API_FILTER} + ${SRCS_PLATFORM_IMPLEMENTATION_CONTACT} + AddressBookController.cpp + ContactConverter.cpp + ContactManagerController.cpp + JSContact.cpp + JSContactArray.cpp + JSContactProperties.cpp + JSAddressBook.cpp + JSAddressBookChangeCallbackManager.cpp + JSAddressBookArray.cpp + JSContactName.cpp + JSContactAccount.cpp + JSContactAnniversary.cpp + JSContactAnniversaryArray.cpp + JSAttributesOfInterestArray.cpp + JSContactAddress.cpp + JSContactAddressArray.cpp + JSContactAddressTypeArray.cpp + JSContactManager.cpp + JSContactPhoneNumber.cpp + JSContactPhoneNumberArray.cpp + JSContactPhoneNumberTypeArray.cpp + JSContactEmailAddress.cpp + JSContactEmailAddressArray.cpp + JSContactEmailAddressTypeArray.cpp + JSContactOrganization.cpp + JSContactOrganizationArray.cpp + JSStringArray.cpp + JSContactWebSite.cpp + JSContactWebSiteArray.cpp + plugin_initializer.cpp + plugin_config.cpp + ../Tizen/FilterConverter.cpp + ../Common/JSTizenException.cpp + ../Common/TizenExceptionData.cpp + ../Common/JSTizenExceptionFactory.cpp +) + +include_directories( + ${INCLUDES_PLATFORM_IMPLEMENTATION_CONTACT} +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_PLATFORM_IMPLEMENTATION_CONTACT} + ${LIBS_COMMON} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION ${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_NAME}) diff --git a/src/standards/Tizen/Contact/ContactConverter.cpp b/src/standards/Tizen/Contact/ContactConverter.cpp new file mode 100755 index 0000000..090fb85 --- /dev/null +++ b/src/standards/Tizen/Contact/ContactConverter.cpp @@ -0,0 +1,1441 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactConverter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include + +#include "ContactConverter.h" +#include "AddressBookController.h" +#include "JSAddressBook.h" +#include "JSAddressBookArray.h" +#include "JSAttributesOfInterestArray.h" +#include "JSContact.h" +#include "JSContactArray.h" +#include "JSContactProperties.h" +#include "JSContactName.h" +#include "JSContactAccount.h" +#include "JSContactAnniversary.h" +#include "JSContactAnniversaryArray.h" +#include "JSContactAddress.h" +#include "JSContactAddressArray.h" +#include "JSContactAddressTypeArray.h" +#include "JSContactManager.h" +#include "JSContactPhoneNumber.h" +#include "JSContactPhoneNumberArray.h" +#include "JSContactPhoneNumberTypeArray.h" +#include "JSContactEmailAddress.h" +#include "JSContactEmailAddressArray.h" +#include "JSContactEmailAddressTypeArray.h" +#include "JSContactOrganization.h" +#include "JSContactOrganizationArray.h" +#include "JSContactWebSite.h" +#include "JSContactWebSiteArray.h" +#include "JSStringArray.h" + +#define CONTACT_ATTRIBUTE_ACCOUNT "account" +#define CONTACT_ATTRIBUTE_ACCOUNT_ID "accountId" +#define CONTACT_ATTRIBUTE_ADDITIONAL_INFORMATION "additionalInformation" +#define CONTACT_ATTRIBUTE_ADDRESSES "addresses" +#define CONTACT_ATTRIBUTE_ANNIVERSARIES "anniversaries" +#define CONTACT_ATTRIBUTE_ATTRIBUTES_OF_INTEREST "attributesOfInterest" +#define CONTACT_ATTRIBUTE_BIRTHDAY "birthday" +#define CONTACT_ATTRIBUTE_CATEGORIES "categories" +#define CONTACT_ATTRIBUTE_CITY "city" +#define CONTACT_ATTRIBUTE_CONTACT_ID "contactId" +#define CONTACT_ATTRIBUTE_CONTACT_URI "contactURI" +#define CONTACT_ATTRIBUTE_COUNTRY "country" +#define CONTACT_ATTRIBUTE_COUNTY "county" +#define CONTACT_ATTRIBUTE_DATE "date" +#define CONTACT_ATTRIBUTE_DEPARTMENT "department" +#define CONTACT_ATTRIBUTE_DISPLAY_NAME "displayName" +#define CONTACT_ATTRIBUTE_EMAIL "email" +#define CONTACT_ATTRIBUTE_EMAILS "emails" +#define CONTACT_ATTRIBUTE_FIRST_NAME "firstName" +#define CONTACT_ATTRIBUTE_ID "id" +#define CONTACT_ATTRIBUTE_IS_FAVORITE "isFavorite" +#define CONTACT_ATTRIBUTE_LABEL "label" +#define CONTACT_ATTRIBUTE_LAST_NAME "lastName" +#define CONTACT_ATTRIBUTE_LAST_UPDATED "lastUpdated" +#define CONTACT_ATTRIBUTE_LOGO_URI "logoURI" +#define CONTACT_ATTRIBUTE_MIDDLE_NAME "middleName" +#define CONTACT_ATTRIBUTE_NAME "name" +#define CONTACT_ATTRIBUTE_NICKNAMES "nicknames" +#define CONTACT_ATTRIBUTE_NOTES "notes" +#define CONTACT_ATTRIBUTE_NUMBER "number" +#define CONTACT_ATTRIBUTE_OFFICE "office" +#define CONTACT_ATTRIBUTE_ORGANIZATION "organization" +#define CONTACT_ATTRIBUTE_PHONE_NUMBERS "phoneNumbers" +#define CONTACT_ATTRIBUTE_PHONETIC_NAME "phoneticName" +#define CONTACT_ATTRIBUTE_PHOTO_URI "photoURI" +#define CONTACT_ATTRIBUTE_POSITION "position" +#define CONTACT_ATTRIBUTE_POSTAL_CODE "postalCode" +#define CONTACT_ATTRIBUTE_PREFIX "prefix" +#define CONTACT_ATTRIBUTE_READ_ONLY "readOnly" +#define CONTACT_ATTRIBUTE_REGION "region" +#define CONTACT_ATTRIBUTE_RINGTONE_URI "ringtoneURI" +#define CONTACT_ATTRIBUTE_ROLE "role" +#define CONTACT_ATTRIBUTE_STREET_ADDRESS "streetAddress" +#define CONTACT_ATTRIBUTE_TITLE "title" +#define CONTACT_ATTRIBUTE_TYPE "type" +#define CONTACT_ATTRIBUTE_TYPES "types" +#define CONTACT_ATTRIBUTE_URL "url" +#define CONTACT_ATTRIBUTE_URLS "urls" + +#define STR_CONTACT_EMAIL_TYPE_WORK "WORK" +#define STR_CONTACT_EMAIL_TYPE_PREF "PREF" +#define STR_CONTACT_EMAIL_TYPE_HOME "HOME" + +#define STR_CONTACT_PHONE_NUMBER_TYPE_WORK "WORK" +#define STR_CONTACT_PHONE_NUMBER_TYPE_PREF "PREF" +#define STR_CONTACT_PHONE_NUMBER_TYPE_HOME "HOME" +#define STR_CONTACT_PHONE_NUMBER_TYPE_VOICE "VOICE" +#define STR_CONTACT_PHONE_NUMBER_TYPE_FAX "FAX" +#define STR_CONTACT_PHONE_NUMBER_TYPE_MSG "MSG" +#define STR_CONTACT_PHONE_NUMBER_TYPE_CELL "CELL" +#define STR_CONTACT_PHONE_NUMBER_TYPE_PAGER "PAGER" +#define STR_CONTACT_PHONE_NUMBER_TYPE_BBS "BBS" +#define STR_CONTACT_PHONE_NUMBER_TYPE_MODEM "MODEM" +#define STR_CONTACT_PHONE_NUMBER_TYPE_CAR "CAR" +#define STR_CONTACT_PHONE_NUMBER_TYPE_ISDN "ISDN" +#define STR_CONTACT_PHONE_NUMBER_TYPE_VIDEO "VIDEO" +#define STR_CONTACT_PHONE_NUMBER_TYPE_PCS "PCS" + +#define STR_CONTACT_ADDRESS_TYPE_WORK "WORK" +#define STR_CONTACT_ADDRESS_TYPE_PREF "PREF" +#define STR_CONTACT_ADDRESS_TYPE_HOME "HOME" + +#define STR_WEBSITE_TYPE_HOMEPAGE "HOMEPAGE" +#define STR_WEBSITE_TYPE_BLOG "BLOG" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Api::Contact; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +std::vector ContactConverter::m_allowedAddressBookProperties; +std::vector ContactConverter::m_allowedContactProperties; +std::vector ContactConverter::m_allowedContactPropertiesProperties; +std::vector ContactConverter::m_allowedContactNameProperties; +std::vector ContactConverter::m_allowedContactAccountProperties; +std::vector ContactConverter::m_allowedContactOrganizationProperties; +std::vector ContactConverter::m_allowedContactWebSiteProperties; +std::vector ContactConverter::m_allowedContactAnniversaryProperties; +std::vector ContactConverter::m_allowedContactAddressProperties; +std::vector ContactConverter::m_allowedContactPhoneNumberProperties; +std::vector ContactConverter::m_allowedContactEmailAddressProperties; + +ContactConverter::ContactConverter(JSContextRef context) : Converter(context) +{ +// //LogDebug("entered"); + static bool init = initializeAllowedProperties(); + (void) init; +} + +ContactConverter::~ContactConverter() +{ +// //LogDebug("entered"); +} + +StringArrayPtr ContactConverter::toStringArray(const JSValueRef &jsValue) +{ + if(JSStringArray::isObjectOfClass(m_context, jsValue)) + return JSStringArray::getStringArray(m_context, jsValue); + + StringArrayPtr result = StringArrayPtr(new StringArray()); + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toString(element)); + } + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const StringArrayPtr &arg) +{ + return JSStringArray::createArray(m_context, arg); +} + +// types converters +ContactEmailAddressType ContactConverter::toContactEmailAddressType(const std::string &arg) +{ +// //LogDebug("entered"); + if (arg == STR_CONTACT_EMAIL_TYPE_WORK) { + return CONTACT_EMAIL_TYPE_WORK; + } else if (arg == STR_CONTACT_EMAIL_TYPE_PREF) { + return CONTACT_EMAIL_TYPE_PREF; + } else if (arg == STR_CONTACT_EMAIL_TYPE_HOME) { + return CONTACT_EMAIL_TYPE_HOME; + } else { + Throw(WrtDeviceApis::Commons::ConversionException); + } + return CONTACT_EMAIL_TYPE_PREF; +} + +std::string ContactConverter::toContactEmailAddressTypeStr(ContactEmailAddressType arg) +{ +// //LogDebug("entered"); + if (arg == CONTACT_EMAIL_TYPE_WORK) { + return STR_CONTACT_EMAIL_TYPE_WORK; + } else if (arg == CONTACT_EMAIL_TYPE_PREF) { + return STR_CONTACT_EMAIL_TYPE_PREF; + } else if (arg == CONTACT_EMAIL_TYPE_HOME) { + return STR_CONTACT_EMAIL_TYPE_HOME; + } else { + Throw(WrtDeviceApis::Commons::ConversionException); + } + return STR_CONTACT_EMAIL_TYPE_PREF; +} + +ContactEmailAddressType ContactConverter::toContactEmailAddressType(const JSValueRef &value) +{ + return toContactEmailAddressType(toString(value)); +} + +JSValueRef ContactConverter::toJSValueRef(ContactEmailAddressType arg) +{ + return toJSValueRef(toContactEmailAddressTypeStr(arg)); +} + +ContactPhoneNumberType ContactConverter::toContactPhoneNumberType(const std::string &arg) +{ +// //LogDebug("entered"); + if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_WORK) { + return CONTACT_PHONE_NUMBER_TYPE_WORK; + } else if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_PREF) { + return CONTACT_PHONE_NUMBER_TYPE_PREF; + } else if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_HOME) { + return CONTACT_PHONE_NUMBER_TYPE_HOME; + } else if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_VOICE) { + return CONTACT_PHONE_NUMBER_TYPE_VOICE; + } else if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_FAX) { + return CONTACT_PHONE_NUMBER_TYPE_FAX; + } else if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_MSG) { + return CONTACT_PHONE_NUMBER_TYPE_MSG; + } else if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_CELL) { + return CONTACT_PHONE_NUMBER_TYPE_CELL; + } else if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_PAGER) { + return CONTACT_PHONE_NUMBER_TYPE_PAGER; + } else if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_BBS) { + return CONTACT_PHONE_NUMBER_TYPE_BBS; + } else if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_MODEM) { + return CONTACT_PHONE_NUMBER_TYPE_MODEM; + } else if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_CAR) { + return CONTACT_PHONE_NUMBER_TYPE_CAR; + } else if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_ISDN) { + return CONTACT_PHONE_NUMBER_TYPE_ISDN; + } else if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_VIDEO) { + return CONTACT_PHONE_NUMBER_TYPE_VIDEO; + } else if (arg == STR_CONTACT_PHONE_NUMBER_TYPE_PCS) { + return CONTACT_PHONE_NUMBER_TYPE_PCS; + } else { + Throw(WrtDeviceApis::Commons::ConversionException); + } + return CONTACT_PHONE_NUMBER_TYPE_WORK; +} + +std::string ContactConverter::toContactPhoneNumberTypeStr(ContactPhoneNumberType arg) +{ +// //LogDebug("entered"); + if (arg == CONTACT_PHONE_NUMBER_TYPE_WORK) { + return STR_CONTACT_PHONE_NUMBER_TYPE_WORK; + } else if (arg == CONTACT_PHONE_NUMBER_TYPE_PREF) { + return STR_CONTACT_PHONE_NUMBER_TYPE_PREF; + } else if (arg == CONTACT_PHONE_NUMBER_TYPE_HOME) { + return STR_CONTACT_PHONE_NUMBER_TYPE_HOME; + } else if (arg == CONTACT_PHONE_NUMBER_TYPE_VOICE) { + return STR_CONTACT_PHONE_NUMBER_TYPE_VOICE; + } else if (arg == CONTACT_PHONE_NUMBER_TYPE_FAX) { + return STR_CONTACT_PHONE_NUMBER_TYPE_FAX; + } else if (arg == CONTACT_PHONE_NUMBER_TYPE_MSG) { + return STR_CONTACT_PHONE_NUMBER_TYPE_MSG; + } else if (arg == CONTACT_PHONE_NUMBER_TYPE_CELL) { + return STR_CONTACT_PHONE_NUMBER_TYPE_CELL; + } else if (arg == CONTACT_PHONE_NUMBER_TYPE_PAGER) { + return STR_CONTACT_PHONE_NUMBER_TYPE_PAGER; + } else if (arg == CONTACT_PHONE_NUMBER_TYPE_BBS) { + return STR_CONTACT_PHONE_NUMBER_TYPE_BBS; + } else if (arg == CONTACT_PHONE_NUMBER_TYPE_MODEM) { + return STR_CONTACT_PHONE_NUMBER_TYPE_MODEM; + } else if (arg == CONTACT_PHONE_NUMBER_TYPE_CAR) { + return STR_CONTACT_PHONE_NUMBER_TYPE_CAR; + } else if (arg == CONTACT_PHONE_NUMBER_TYPE_ISDN) { + return STR_CONTACT_PHONE_NUMBER_TYPE_ISDN; + } else if (arg == CONTACT_PHONE_NUMBER_TYPE_VIDEO) { + return STR_CONTACT_PHONE_NUMBER_TYPE_VIDEO; + } else if (arg == CONTACT_PHONE_NUMBER_TYPE_PCS) { + return STR_CONTACT_PHONE_NUMBER_TYPE_PCS; + } else { + Throw(WrtDeviceApis::Commons::ConversionException); + } + return STR_CONTACT_PHONE_NUMBER_TYPE_WORK; +} + +ContactPhoneNumberType ContactConverter::toContactPhoneNumberType(const JSValueRef &value) +{ + return toContactPhoneNumberType(toString(value)); +} + +JSValueRef ContactConverter::toJSValueRef(ContactPhoneNumberType arg) +{ + return toJSValueRef(toContactPhoneNumberTypeStr(arg)); +} + +ContactAddressType ContactConverter::toContactAddressType(const std::string &arg) +{ +// //LogDebug("entered"); + if (arg == STR_CONTACT_ADDRESS_TYPE_WORK) { + return CONTACT_ADDRESS_TYPE_WORK; + } else if (arg == STR_CONTACT_ADDRESS_TYPE_PREF) { + return CONTACT_ADDRESS_TYPE_PREF; + } else if (arg == STR_CONTACT_ADDRESS_TYPE_HOME) { + return CONTACT_ADDRESS_TYPE_HOME; + } else { + Throw(WrtDeviceApis::Commons::ConversionException); + } + return CONTACT_ADDRESS_TYPE_PREF; +} +std::string ContactConverter::toContactAddressTypeStr(ContactAddressType arg) +{ +// //LogDebug("entered"); + if (arg == CONTACT_ADDRESS_TYPE_WORK) { + return STR_CONTACT_ADDRESS_TYPE_WORK; + } else if (arg == CONTACT_ADDRESS_TYPE_PREF) { + return STR_CONTACT_ADDRESS_TYPE_PREF; + } else if (arg == CONTACT_ADDRESS_TYPE_HOME) { + return STR_CONTACT_ADDRESS_TYPE_HOME; + } else { + Throw(WrtDeviceApis::Commons::ConversionException); + } + return STR_CONTACT_ADDRESS_TYPE_PREF; +} + +ContactAddressType ContactConverter::toContactAddressType(const JSValueRef &value) +{ + return toContactAddressType(toString(value)); +} + +JSValueRef ContactConverter::toJSValueRef(ContactAddressType arg) +{ + return toJSValueRef(toContactAddressTypeStr(arg)); +} + +ContactWebSiteType ContactConverter::toContactWebSiteType(const std::string &arg) +{ + //LogDebug("entered"); + if (arg == STR_WEBSITE_TYPE_HOMEPAGE) { + return WEBSITE_TYPE_HOMEPAGE; + } else if (arg == STR_WEBSITE_TYPE_BLOG) { + return WEBSITE_TYPE_BLOG; + } else { + Throw(WrtDeviceApis::Commons::ConversionException); + } + return WEBSITE_TYPE_HOMEPAGE; +} + +std::string ContactConverter::toContactWebSiteTypeStr(ContactWebSiteType arg) +{ + //LogDebug("entered"); + if (arg == WEBSITE_TYPE_HOMEPAGE) { + return STR_WEBSITE_TYPE_HOMEPAGE; + } else if (arg == WEBSITE_TYPE_BLOG) { + return STR_WEBSITE_TYPE_BLOG; + } else { + Throw(WrtDeviceApis::Commons::ConversionException); + } + return STR_WEBSITE_TYPE_HOMEPAGE; +} + +ContactWebSiteType ContactConverter::toContactWebSiteType(const JSValueRef &value) +{ + return toContactWebSiteType(toString(value)); +} + +JSValueRef ContactConverter::toJSValueRef(ContactWebSiteType arg) +{ + return toJSValueRef(toContactWebSiteTypeStr(arg)); +} + +ContactCapabilityType ContactConverter::toContactCapabilityType(const JSValueRef &value) +{ + int result = toInt(value); + if(HAS_VIDEO_CAPABILITY != result && + HAS_VOICE_CAPABILITY != result && + HAS_CAMERA_CAPABILITY != result) + Throw(WrtDeviceApis::Commons::ConversionException); + + return static_cast(result); +} + +std::string ContactConverter::toAttributesOfInterest(const JSValueRef &value) +{ + // TODO validate + return toString(value); +} + +JSValueRef ContactConverter::toJSValueRef(const IAddressBookPtr &arg) +{ + //LogDebug("entered"); + AddressBookController *priv = new AddressBookController(m_context, arg); + return JSObjectMake(m_context, JSAddressBook::getClassRef(), priv); +} + +IAddressBookPtr ContactConverter::toAddressBook(const JSValueRef &jsValue) +{ + if(!JSAddressBook::isObjectOfClass(m_context, jsValue)) + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + + return JSAddressBook::getAddressBook(m_context, jsValue); +} + +JSValueRef ContactConverter::toJSValueRef(const IAddressBookArrayPtr &arg) +{ + int size = arg->size(); + if(size == 0) + return JSValueMakeNull(m_context); + + JSObjectRef resultObject = JSCreateArrayObject(m_context, 0, NULL); + if (!resultObject) + ThrowMsg(ConversionException, "Can not create array object."); + + for(int i = 0; i < size; i++) + { + JSValueRef jsvalue = toJSValueRef(arg->at(i)); + if (!JSSetArrayElement(m_context, resultObject, i, jsvalue)) + ThrowMsg(ConversionException, "Can not fill address book array."); + } + + return static_cast(resultObject); +} + +IAddressBookArrayPtr ContactConverter::toAddressBookArray(const JSValueRef &jsValue) +{ + if(JSAddressBookArray::isObjectOfClass(m_context, jsValue)) + return JSAddressBookArray::getAddressBookArray(m_context, jsValue); + + IAddressBookArrayPtr result(new IAddressBookArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toAddressBook(element)); + } + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContact::getClassRef(), arg); +} + +ContactPtr ContactConverter::toContact(const JSValueRef &jsValue) +{ + if(!JSContact::isObjectOfClass(m_context, jsValue)) + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + + return JSContact::getContact(m_context, jsValue); +} + +JSValueRef ContactConverter::toJSValueRef(const ContactArrayPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactArray::getClassRef(), arg); +} + +ContactArrayPtr ContactConverter::toContactArray(const JSValueRef &jsValue) +{ + if(JSContactArray::isObjectOfClass(m_context, jsValue)) + return JSContactArray::getContactArray(m_context, jsValue); + + ContactArrayPtr result = ContactArrayPtr(new ContactArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toContact(element)); + } + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactPropertiesPtr &arg) +{ + // TODO make user object + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactProperties::getClassRef(), arg); +} + +ContactPropertiesPtr ContactConverter::toContactProperties(const JSValueRef &jsValue) +{ + if(JSContactProperties::isObjectOfClass(m_context, jsValue)) + return JSContactProperties::getContactProperties(m_context, jsValue); + + Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedContactPropertiesProperties, jsValue)) { + LogError("invalid properties in contact object"); + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + } + + const ScopedJSStringRef nameStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_NAME)); + const ScopedJSStringRef accountStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_ACCOUNT)); + const ScopedJSStringRef addressesStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_ADDRESSES)); + const ScopedJSStringRef photoURIStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_PHOTO_URI)); + const ScopedJSStringRef phoneNumbersStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_PHONE_NUMBERS)); + const ScopedJSStringRef emailsStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_EMAILS)); + const ScopedJSStringRef birthdayStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_BIRTHDAY)); + const ScopedJSStringRef anniversariesStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_ANNIVERSARIES)); + const ScopedJSStringRef organizationStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_ORGANIZATION)); + const ScopedJSStringRef notesStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_NOTES)); + const ScopedJSStringRef urlsStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_URLS)); + const ScopedJSStringRef isFavoriteStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_IS_FAVORITE)); + const ScopedJSStringRef ringtoneURIStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_RINGTONE_URI)); + const ScopedJSStringRef categoriesStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_CATEGORIES)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef nameData = JSObjectGetProperty(m_context, jsObject, nameStr.get(), NULL); + JSValueRef accountData = JSObjectGetProperty(m_context, jsObject, accountStr.get(), NULL); + JSValueRef addressesData = JSObjectGetProperty(m_context, jsObject, addressesStr.get(), NULL); + JSValueRef photoURIData = JSObjectGetProperty(m_context, jsObject, photoURIStr.get(), NULL); + JSValueRef phoneNumbersData = JSObjectGetProperty(m_context, jsObject, phoneNumbersStr.get(), NULL); + JSValueRef emailsData = JSObjectGetProperty(m_context, jsObject, emailsStr.get(), NULL); + JSValueRef birthdayData = JSObjectGetProperty(m_context, jsObject, birthdayStr.get(), NULL); + JSValueRef anniversariesData = JSObjectGetProperty(m_context, jsObject, anniversariesStr.get(), NULL); + JSValueRef organizationData = JSObjectGetProperty(m_context, jsObject, organizationStr.get(), NULL); + JSValueRef notesData = JSObjectGetProperty(m_context, jsObject, notesStr.get(), NULL); + JSValueRef urlsData = JSObjectGetProperty(m_context, jsObject, urlsStr.get(), NULL); + JSValueRef isFavoriteData = JSObjectGetProperty(m_context, jsObject, isFavoriteStr.get(), NULL); + JSValueRef ringtoneURIData = JSObjectGetProperty(m_context, jsObject, ringtoneURIStr.get(), NULL); + JSValueRef categoriesData = JSObjectGetProperty(m_context, jsObject, categoriesStr.get(), NULL); + + ContactNamePtr name; + ContactAccountPtr account; + ContactAddressArrayPtr addresses; + std::string photoURI; + ContactPhoneNumberArrayPtr phoneNumbers; + ContactEmailAddressArrayPtr emails; + tm birthday; + ContactAnniversaryArrayPtr anniversaries; + ContactOrganizationPtr organization; + StringArrayPtr notes; + ContactWebSiteArrayPtr urls; + bool isFavorite; + std::string ringtoneURI; + StringArrayPtr categories; + + ContactPropertiesPtr result = ContactPropertiesPtr(new ContactProperties()); + if (!result) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, nameData)) { + name = toContactName(nameData); + result->setName(name); + } + + if (!JSValueIsUndefined(m_context, accountData)) { + account = toContactAccount(accountData); + result->setAccount(account); + } + + if (!JSValueIsUndefined(m_context, addressesData)) { + addresses = toContactAddressArray(addressesData); + result->setAddresses(addresses); + } + + if (!JSValueIsUndefined(m_context, photoURIData)) { + photoURI = toString(photoURIData); + result->setPhotoURI(photoURI); + } + + if (!JSValueIsUndefined(m_context, phoneNumbersData)) { + phoneNumbers = toContactPhoneNumberArray(phoneNumbersData); + result->setPhoneNumbers(phoneNumbers); + } + + if (!JSValueIsUndefined(m_context, emailsData)) { + emails = toContactEmailAddressArray(emailsData); + result->setEmails(emails); + } + + if (!JSValueIsUndefined(m_context, birthdayData)) { + birthday = toDateTm(birthdayData); + result->setBirthday(birthday); + } + + if (!JSValueIsUndefined(m_context, anniversariesData)) { + anniversaries = toContactAnniversaryArray(anniversariesData); + result->setAnniversaries(anniversaries); + } + + if (!JSValueIsUndefined(m_context, organizationData)) { + organization = toContactOrganization(organizationData); + result->setOrganization(organization); + } + + if (!JSValueIsUndefined(m_context, notesData)) { + notes = toStringArray(notesData); + result->setNotes(notes); + } + + if (!JSValueIsUndefined(m_context, urlsData)) { + urls = toContactWebSiteArray(urlsData); + result->setUrls(urls); + } + + if (!JSValueIsUndefined(m_context, isFavoriteData)) { + isFavorite = toBool(isFavoriteData); + result->setIsFavorite(isFavorite); + } + + if (!JSValueIsUndefined(m_context, ringtoneURIData)) { + ringtoneURI = toString(ringtoneURIData); + result->setRingtoneURI(ringtoneURI); + } + + if (!JSValueIsUndefined(m_context, categoriesData)) { + categories = toStringArray(categoriesData); + result->setCategories(categories); + } + + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactPropertiesArrayPtr &arg) +{ + //LogDebug("entered"); + int size = arg->size(); + if(size == 0) + return JSValueMakeNull(m_context); + + JSObjectRef resultObject = JSCreateArrayObject(m_context, 0, NULL); + if (!resultObject) + ThrowMsg(ConversionException, "Can not create array object."); + + for(int i = 0; i < size; i++) + { + JSValueRef jsvalue = toJSValueRef(arg->at(i)); + if (!JSSetArrayElement(m_context, resultObject, i, jsvalue)) + ThrowMsg(ConversionException, "Can not fill contact properties array."); + } + + return static_cast(resultObject); +} + +ContactPropertiesArrayPtr ContactConverter::toContactPropertiesArray(const JSValueRef &jsValue) +{ + ContactPropertiesArrayPtr result = ContactPropertiesArrayPtr(new ContactPropertiesArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toContactProperties(element)); + } + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactNamePtr &arg) +{ + // TODO make user object + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactName::getClassRef(), arg); +} + +ContactNamePtr ContactConverter::toContactName(const JSValueRef &jsValue) +{ + if(JSContactName::isObjectOfClass(m_context, jsValue)) + return JSContactName::getContactName(m_context, jsValue); + + Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedContactNameProperties, jsValue)) { + LogError("invalid properties in contact object"); + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + } + + const ScopedJSStringRef prefixStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_PREFIX)); + const ScopedJSStringRef firstNameStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_FIRST_NAME)); + const ScopedJSStringRef middleNameStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_MIDDLE_NAME)); + const ScopedJSStringRef lastNameStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_LAST_NAME)); + const ScopedJSStringRef nicknamesStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_NICKNAMES)); + const ScopedJSStringRef phoneticNameStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_PHONETIC_NAME)); + const ScopedJSStringRef displayNameStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_DISPLAY_NAME)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef prefixData = JSObjectGetProperty(m_context, jsObject, prefixStr.get(), NULL); + JSValueRef firstNameData = JSObjectGetProperty(m_context, jsObject, firstNameStr.get(), NULL); + JSValueRef middleNameData = JSObjectGetProperty(m_context, jsObject, middleNameStr.get(), NULL); + JSValueRef lastNameData = JSObjectGetProperty(m_context, jsObject, lastNameStr.get(), NULL); + JSValueRef nicknamesData = JSObjectGetProperty(m_context, jsObject, nicknamesStr.get(), NULL); + JSValueRef phoneticNameData = JSObjectGetProperty(m_context, jsObject, phoneticNameStr.get(), NULL); + JSValueRef displayNameData = JSObjectGetProperty(m_context, jsObject, displayNameStr.get(), NULL); + + std::string prefix; + std::string firstName; + std::string middleName; + std::string lastName; + StringArrayPtr nicknames; + std::string phoneticName; + std::string displayName; + + ContactNamePtr result = ContactNamePtr(new ContactName()); + if (!result) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, prefixData)) { + prefix = toString(prefixData); + result->setPrefix(prefix); + } + + if (!JSValueIsUndefined(m_context, firstNameData)) { + firstName = toString(firstNameData); + result->setFirstName(firstName); + } + + if (!JSValueIsUndefined(m_context, middleNameData)) { + middleName = toString(middleNameData); + result->setMiddleName(middleName); + } + + if (!JSValueIsUndefined(m_context, lastNameData)) { + lastName = toString(lastNameData); + result->setLastName(lastName); + } + + if (!JSValueIsUndefined(m_context, nicknamesData)) { + nicknames = toStringArray(nicknamesData); + result->setNicknames(nicknames); + } + + if (!JSValueIsUndefined(m_context, phoneticNameData)) { + phoneticName = toString(phoneticNameData); + result->setPhoneticName(phoneticName); + } + + if (!JSValueIsUndefined(m_context, displayNameData)) { + displayName = toString(displayNameData); + result->setDisplayName(displayName); + } + + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactAccountPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactAccount::getClassRef(), arg); +} + +ContactAccountPtr ContactConverter::toContactAccount(const JSValueRef &jsValue) +{ + if(JSContactAccount::isObjectOfClass(m_context, jsValue)) + return JSContactAccount::getContactAccount(m_context, jsValue); + + Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedContactAccountProperties, jsValue)) { + LogError("invalid properties in contact object"); + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + } + + const ScopedJSStringRef accountIdStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_ACCOUNT_ID)); + const ScopedJSStringRef contactURIStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_CONTACT_URI)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef accountIdData = JSObjectGetProperty(m_context, jsObject, accountIdStr.get(), NULL); + JSValueRef contactURIData = JSObjectGetProperty(m_context, jsObject, contactURIStr.get(), NULL); + + std::string accountId; + std::string contactURI; + + ContactAccountPtr result(new ContactAccount()); + if (!result) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, accountIdData)) { + accountId = toString(accountIdData); + result->setAccountId(accountId); + } + + if (!JSValueIsUndefined(m_context, contactURIData)) { + contactURI = toString(contactURIData); + result->setContactURI(contactURI); + } + + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactAnniversaryPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactAnniversary::getClassRef(), arg); +} + +ContactAnniversaryPtr ContactConverter::toContactAnniversary(const JSValueRef &jsValue) +{ + if(JSContactAnniversary::isObjectOfClass(m_context, jsValue)) + return JSContactAnniversary::getContactAnniversary(m_context, jsValue); + + Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedContactAnniversaryProperties, jsValue)) { + LogError("invalid properties in contact object"); + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + } + + const ScopedJSStringRef dateStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_DATE)); + const ScopedJSStringRef labelStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_LABEL)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef dateData = JSObjectGetProperty(m_context, jsObject, dateStr.get(), NULL); + JSValueRef labelData = JSObjectGetProperty(m_context, jsObject, labelStr.get(), NULL); + + std::tm date; + std::string label; + + ContactAnniversaryPtr result(new ContactAnniversary()); + if (!result) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, dateData)) { + date = toDateTm(dateData); + result->setDate(date); + } + + if (!JSValueIsUndefined(m_context, labelData)) { + label = toString(labelData); + result->setLabel(label); + } + + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactAnniversaryArrayPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactAnniversaryArray::getClassRef(), arg); +} + +ContactAnniversaryArrayPtr ContactConverter::toContactAnniversaryArray(const JSValueRef &jsValue) +{ + if(JSContactAnniversaryArray::isObjectOfClass(m_context, jsValue)) + return JSContactAnniversaryArray::getContactAnniversaryArray(m_context, jsValue); + + ContactAnniversaryArrayPtr result(new ContactAnniversaryArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toContactAnniversary(element)); + } + return result; +} + +JSValueRef ContactConverter::toJSValueRefAttributesOfInterestArray(const AttributesOfInterestArrayPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSAttributesOfInterestArray::getClassRef(), arg); +} + +AttributesOfInterestArrayPtr ContactConverter::toAttributesOfInterestArray(const JSValueRef &jsValue) +{ + if(JSAttributesOfInterestArray::isObjectOfClass(m_context, jsValue)) + return JSAttributesOfInterestArray::getAttributesOfInterestArray(m_context, jsValue); + + AttributesOfInterestArrayPtr result(new AttributesOfInterestArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toAttributesOfInterest(element)); + } + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactAddressPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactAddress::getClassRef(), arg); +} + +ContactAddressPtr ContactConverter::toContactAddress(const JSValueRef &jsValue) +{ + if(JSContactAddress::isObjectOfClass(m_context, jsValue)) + return JSContactAddress::getContactAddress(m_context, jsValue); + + Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedContactAddressProperties, jsValue)) { + LogError("invalid properties in contact object"); + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + } + + const ScopedJSStringRef countryStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_COUNTRY)); + const ScopedJSStringRef regionStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_REGION)); + const ScopedJSStringRef cityStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_CITY)); + const ScopedJSStringRef streetAddressStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_STREET_ADDRESS)); + const ScopedJSStringRef additionalInformationStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_ADDITIONAL_INFORMATION)); + const ScopedJSStringRef postalCodeStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_POSTAL_CODE)); + const ScopedJSStringRef typesStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_TYPES)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef countryData = JSObjectGetProperty(m_context, jsObject, countryStr.get(), NULL); + JSValueRef regionData = JSObjectGetProperty(m_context, jsObject, regionStr.get(), NULL); + JSValueRef cityData = JSObjectGetProperty(m_context, jsObject, cityStr.get(), NULL); + JSValueRef streetAddressData = JSObjectGetProperty(m_context, jsObject, streetAddressStr.get(), NULL); + JSValueRef additionalInformationData = JSObjectGetProperty(m_context, jsObject, additionalInformationStr.get(), NULL); + JSValueRef postalCodeData = JSObjectGetProperty(m_context, jsObject, postalCodeStr.get(), NULL); + JSValueRef typesData = JSObjectGetProperty(m_context, jsObject, typesStr.get(), NULL); + + std::string country; + std::string region; + std::string city; + std::string streetAddress; + std::string additionalInformation; + std::string postalCode; + ContactAddressTypeArrayPtr types; + + ContactAddressPtr result(new ContactAddress()); + if (!result) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, countryData)) { + country = toString(countryData); + result->setCountry(country); + } + + if (!JSValueIsUndefined(m_context, regionData)) { + region = toString(regionData); + result->setRegion(region); + } + + if (!JSValueIsUndefined(m_context, cityData)) { + city = toString(cityData); + result->setCity(city); + } + + if (!JSValueIsUndefined(m_context, streetAddressData)) { + streetAddress = toString(streetAddressData); + result->setStreetAddress(streetAddress); + } + + if (!JSValueIsUndefined(m_context, additionalInformationData)) { + additionalInformation = toString(additionalInformationData); + result->setAdditionalInformation(additionalInformation); + } + + if (!JSValueIsUndefined(m_context, postalCodeData)) { + postalCode = toString(postalCodeData); + result->setPostalCode(postalCode); + } + + if (!JSValueIsUndefined(m_context, typesData)) { + types = toContactAddressTypeArray(typesData); + result->setTypes(types); + } + + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactAddressArrayPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactAddressArray::getClassRef(), arg); +} + +ContactAddressArrayPtr ContactConverter::toContactAddressArray(const JSValueRef &jsValue) +{ + if(JSContactAddressArray::isObjectOfClass(m_context, jsValue)) + return JSContactAddressArray::getContactAddressArray(m_context, jsValue); + + ContactAddressArrayPtr result(new ContactAddressArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toContactAddress(element)); + } + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactAddressTypeArrayPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactAddressTypeArray::getClassRef(), arg); +} + +ContactAddressTypeArrayPtr ContactConverter::toContactAddressTypeArray(const JSValueRef &jsValue) +{ + if(JSContactAddressTypeArray::isObjectOfClass(m_context, jsValue)) + return JSContactAddressTypeArray::getContactAddressTypeArray(m_context, jsValue); + + ContactAddressTypeArrayPtr result(new ContactAddressTypeArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toContactAddressType(element)); + } + return result; +} + +//JSValueRef ContactConverter::toJSValueRef(const ContactCapabilityTypeArrayPtr &arg) +//{ +// //LogDebug("entered"); +// return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactCapabilityTypeArray::getClassRef(), arg); +//} +// +//ContactCapabilityTypeArrayPtr ContactConverter::toContactCapabilityTypeArray(const JSValueRef &jsValue) +//{ +// if(JSContactCapabilityTypeArray::isObjectOfClass(m_context, jsValue)) +// return JSContactCapabilityTypeArray::getContactCapabilityTypeArray(m_context, jsValue); +// +// ContactCapabilityTypeArrayPtr result(new ContactCapabilityTypeArray()); +// +// JSObjectRef jsObject = toJSObjectRef(jsValue); +// for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { +// JSValueRef element = JSGetArrayElement(m_context, jsObject, i); +// result->push_back(toContactCapabilityType(element)); +// } +// return result; +//} + +JSValueRef ContactConverter::toJSValueRef(const ContactPhoneNumberPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactPhoneNumber::getClassRef(), arg); +} + +ContactPhoneNumberPtr ContactConverter::toContactPhoneNumber(const JSValueRef &jsValue) +{ + if(JSContactPhoneNumber::isObjectOfClass(m_context, jsValue)) + return JSContactPhoneNumber::getContactPhoneNumber(m_context, jsValue); + + Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedContactPhoneNumberProperties, jsValue)) { + LogError("invalid properties in contact object"); + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + } + + const ScopedJSStringRef numberStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_NUMBER)); + const ScopedJSStringRef typesStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_TYPES)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef numberData = JSObjectGetProperty(m_context, jsObject, numberStr.get(), NULL); + JSValueRef typesData = JSObjectGetProperty(m_context, jsObject, typesStr.get(), NULL); + + std::string number; + StringArrayPtr types; + + ContactPhoneNumberPtr result(new ContactPhoneNumber()); + if (!result) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, numberData)) { + number = toString(numberData); + result->setNumber(number); + } + + if (!JSValueIsUndefined(m_context, typesData)) { + types = toStringArray(typesData); + result->setTypes(types); + } else { + result->addType("VOICE"); + } + + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactPhoneNumberArrayPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactPhoneNumberArray::getClassRef(), arg); +} + +ContactPhoneNumberArrayPtr ContactConverter::toContactPhoneNumberArray(const JSValueRef &jsValue) +{ + if(JSContactPhoneNumberArray::isObjectOfClass(m_context, jsValue)) + return JSContactPhoneNumberArray::getContactPhoneNumberArray(m_context, jsValue); + + ContactPhoneNumberArrayPtr result(new ContactPhoneNumberArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toContactPhoneNumber(element)); + } + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactPhoneNumberTypeArrayPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactPhoneNumberTypeArray::getClassRef(), arg); +} + +ContactPhoneNumberTypeArrayPtr ContactConverter::toContactPhoneNumberTypeArray(const JSValueRef &jsValue) +{ + if(JSContactPhoneNumberTypeArray::isObjectOfClass(m_context, jsValue)) + return JSContactPhoneNumberTypeArray::getContactPhoneNumberTypeArray(m_context, jsValue); + + ContactPhoneNumberTypeArrayPtr result(new ContactPhoneNumberTypeArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toContactPhoneNumberType(element)); + } + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactEmailAddressPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactEmailAddress::getClassRef(), arg); +} + +ContactEmailAddressPtr ContactConverter::toContactEmailAddress(const JSValueRef &jsValue) +{ + if(JSContactEmailAddress::isObjectOfClass(m_context, jsValue)) + return JSContactEmailAddress::getContactEmailAddress(m_context, jsValue); + + Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedContactEmailAddressProperties, jsValue)) { + LogError("invalid properties in contact object"); + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + } + + const ScopedJSStringRef emailStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_EMAIL)); + const ScopedJSStringRef typesStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_TYPES)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + + JSValueRef emailData = JSObjectGetProperty(m_context, jsObject, emailStr.get(), NULL); + JSValueRef typesData = JSObjectGetProperty(m_context, jsObject, typesStr.get(), NULL); + + + std::string email; + ContactEmailAddressTypeArrayPtr types; + + ContactEmailAddressPtr result(new ContactEmailAddress()); + if (!result) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, emailData)) { + email = toString(emailData); + result->setEmail(email); + } + + if (!JSValueIsUndefined(m_context, typesData)) { + types = toContactEmailAddressTypeArray(typesData); + result->setTypes(types); + } else { + result->addType(CONTACT_EMAIL_TYPE_PREF); + } + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactEmailAddressArrayPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactEmailAddressArray::getClassRef(), arg); +} + +ContactEmailAddressArrayPtr ContactConverter::toContactEmailAddressArray(const JSValueRef &jsValue) +{ + if(JSContactEmailAddressArray::isObjectOfClass(m_context, jsValue)) + return JSContactEmailAddressArray::getContactEmailAddressArray(m_context, jsValue); + + ContactEmailAddressArrayPtr result(new ContactEmailAddressArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toContactEmailAddress(element)); + } + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactEmailAddressTypeArrayPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactEmailAddressTypeArray::getClassRef(), arg); +} + +ContactEmailAddressTypeArrayPtr ContactConverter::toContactEmailAddressTypeArray(const JSValueRef &jsValue) +{ + if(JSContactEmailAddressTypeArray::isObjectOfClass(m_context, jsValue)) + return JSContactEmailAddressTypeArray::getContactEmailAddressTypeArray(m_context, jsValue); + + ContactEmailAddressTypeArrayPtr result(new ContactEmailAddressTypeArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toContactEmailAddressType(element)); + } + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactOrganizationPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactOrganization::getClassRef(), arg); +} + +ContactOrganizationPtr ContactConverter::toContactOrganization(const JSValueRef &jsValue) +{ + if(JSContactOrganization::isObjectOfClass(m_context, jsValue)) + return JSContactOrganization::getContactOrganization(m_context, jsValue); + + Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedContactOrganizationProperties, jsValue)) { + LogError("invalid properties in contact object"); + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + } + + const ScopedJSStringRef nameStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_NAME)); + const ScopedJSStringRef departmentStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_DEPARTMENT)); + const ScopedJSStringRef titleStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_TITLE)); + const ScopedJSStringRef roleStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_ROLE)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef nameData = JSObjectGetProperty(m_context, jsObject, nameStr.get(), NULL); + JSValueRef departmentData = JSObjectGetProperty(m_context, jsObject, departmentStr.get(), NULL); + JSValueRef titleData = JSObjectGetProperty(m_context, jsObject, titleStr.get(), NULL); + JSValueRef roleData = JSObjectGetProperty(m_context, jsObject, roleStr.get(), NULL); + + std::string name; + std::string department; + std::string title; + std::string role; + + ContactOrganizationPtr result(new ContactOrganization()); + if (!result) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, nameData)) { + name = toString(nameData); + result->setName(name); + } + + if (!JSValueIsUndefined(m_context, departmentData)) { + department = toString(departmentData); + result->setDepartment(department); + } + + if (!JSValueIsUndefined(m_context, titleData)) { + title = toString(titleData); + result->setTitle(title); + } + + if (!JSValueIsUndefined(m_context, roleData)) { + role = toString(roleData); + result->setRole(role); + } + + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactOrganizationArrayPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactOrganizationArray::getClassRef(), arg); +} + +ContactOrganizationArrayPtr ContactConverter::toContactOrganizationArray(const JSValueRef &jsValue) +{ + if(JSContactOrganizationArray::isObjectOfClass(m_context, jsValue)) + return JSContactOrganizationArray::getContactOrganizationArray(m_context, jsValue); + + ContactOrganizationArrayPtr result(new ContactOrganizationArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toContactOrganization(element)); + } + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactWebSitePtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactWebSite::getClassRef(), arg); +} + +ContactWebSitePtr ContactConverter::toContactWebSite(const JSValueRef &jsValue) +{ + if(JSContactWebSite::isObjectOfClass(m_context, jsValue)) + return JSContactWebSite::getContactWebSite(m_context, jsValue); + + Validator validator(m_context); + if (!validator.checkArrayKeys(m_allowedContactWebSiteProperties, jsValue)) { + LogError("invalid properties in contact object"); + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + } + + const ScopedJSStringRef urlStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_URL)); + const ScopedJSStringRef typeStr(JSStringCreateWithUTF8CString(CONTACT_ATTRIBUTE_TYPE)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef urlData = JSObjectGetProperty(m_context, jsObject, urlStr.get(), NULL); + JSValueRef typeData = JSObjectGetProperty(m_context, jsObject, typeStr.get(), NULL); + + std::string url; + ContactWebSiteType type; + + ContactWebSitePtr result(new ContactWebSite()); + if (!result) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, urlData)) { + url = toString(urlData); + result->setUrl(url); + } + + if (!JSValueIsUndefined(m_context, typeData)) { + type = toContactWebSiteType(typeData); + result->setType(type); + } + + return result; +} + +JSValueRef ContactConverter::toJSValueRef(const ContactWebSiteArrayPtr &arg) +{ + //LogDebug("entered"); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSContactWebSiteArray::getClassRef(), arg); +} + +ContactWebSiteArrayPtr ContactConverter::toContactWebSiteArray(const JSValueRef &jsValue) +{ + if(JSContactWebSiteArray::isObjectOfClass(m_context, jsValue)) + return JSContactWebSiteArray::getContactWebSiteArray(m_context, jsValue); + + ContactWebSiteArrayPtr result(new ContactWebSiteArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toContactWebSite(element)); + } + return result; +} + +bool ContactConverter::initializeAllowedProperties() +{ + m_allowedAddressBookProperties.push_back(CONTACT_ATTRIBUTE_NAME); + + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_ID); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_READ_ONLY); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_LAST_UPDATED); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_NAME); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_ACCOUNT); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_ADDRESSES); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_PHOTO_URI ); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_PHONE_NUMBERS); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_EMAILS); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_BIRTHDAY); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_ANNIVERSARIES); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_ORGANIZATION); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_NOTES); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_URLS); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_IS_FAVORITE); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_RINGTONE_URI); + m_allowedContactProperties.push_back(CONTACT_ATTRIBUTE_CATEGORIES); + + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_NAME); + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_ACCOUNT); + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_ADDRESSES); + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_PHOTO_URI ); + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_PHONE_NUMBERS); + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_EMAILS); + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_BIRTHDAY); + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_ANNIVERSARIES); + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_ORGANIZATION); + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_NOTES); + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_URLS); + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_IS_FAVORITE); + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_RINGTONE_URI); + m_allowedContactPropertiesProperties.push_back(CONTACT_ATTRIBUTE_CATEGORIES); + + m_allowedContactNameProperties.push_back(CONTACT_ATTRIBUTE_PREFIX); + m_allowedContactNameProperties.push_back(CONTACT_ATTRIBUTE_FIRST_NAME); + m_allowedContactNameProperties.push_back(CONTACT_ATTRIBUTE_MIDDLE_NAME); + m_allowedContactNameProperties.push_back(CONTACT_ATTRIBUTE_LAST_NAME); + m_allowedContactNameProperties.push_back(CONTACT_ATTRIBUTE_NICKNAMES); + m_allowedContactNameProperties.push_back(CONTACT_ATTRIBUTE_PHONETIC_NAME); + m_allowedContactNameProperties.push_back(CONTACT_ATTRIBUTE_DISPLAY_NAME); + + m_allowedContactAccountProperties.push_back(CONTACT_ATTRIBUTE_ACCOUNT_ID); + m_allowedContactAccountProperties.push_back(CONTACT_ATTRIBUTE_CONTACT_URI); + + m_allowedContactOrganizationProperties.push_back(CONTACT_ATTRIBUTE_NAME); + m_allowedContactOrganizationProperties.push_back(CONTACT_ATTRIBUTE_DEPARTMENT); + m_allowedContactOrganizationProperties.push_back(CONTACT_ATTRIBUTE_OFFICE); + m_allowedContactOrganizationProperties.push_back(CONTACT_ATTRIBUTE_TITLE); + m_allowedContactOrganizationProperties.push_back(CONTACT_ATTRIBUTE_ROLE); + m_allowedContactOrganizationProperties.push_back(CONTACT_ATTRIBUTE_LOGO_URI); + + m_allowedContactWebSiteProperties.push_back(CONTACT_ATTRIBUTE_URL); + m_allowedContactWebSiteProperties.push_back(CONTACT_ATTRIBUTE_TYPE); + + m_allowedContactAnniversaryProperties.push_back(CONTACT_ATTRIBUTE_DATE); + m_allowedContactAnniversaryProperties.push_back(CONTACT_ATTRIBUTE_LABEL); + + m_allowedContactAddressProperties.push_back(CONTACT_ATTRIBUTE_COUNTRY); + m_allowedContactAddressProperties.push_back(CONTACT_ATTRIBUTE_REGION); + m_allowedContactAddressProperties.push_back(CONTACT_ATTRIBUTE_CITY); + m_allowedContactAddressProperties.push_back(CONTACT_ATTRIBUTE_STREET_ADDRESS); + m_allowedContactAddressProperties.push_back(CONTACT_ATTRIBUTE_ADDITIONAL_INFORMATION); + m_allowedContactAddressProperties.push_back(CONTACT_ATTRIBUTE_POSTAL_CODE); + m_allowedContactAddressProperties.push_back(CONTACT_ATTRIBUTE_TYPES); + + m_allowedContactPhoneNumberProperties.push_back(CONTACT_ATTRIBUTE_NUMBER); + m_allowedContactPhoneNumberProperties.push_back(CONTACT_ATTRIBUTE_TYPES); + + m_allowedContactEmailAddressProperties.push_back(CONTACT_ATTRIBUTE_EMAIL); + m_allowedContactEmailAddressProperties.push_back(CONTACT_ATTRIBUTE_TYPES); + + return true; +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/ContactConverter.h b/src/standards/Tizen/Contact/ContactConverter.h new file mode 100755 index 0000000..904c8a0 --- /dev/null +++ b/src/standards/Tizen/Contact/ContactConverter.h @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactConverter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_JS_CONTACT_CONVERTER_H_ +#define _TIZEN_JS_CONTACT_CONVERTER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +class ContactConverter : public WrtDeviceApis::CommonsJavaScript::Converter +{ +public: + using WrtDeviceApis::CommonsJavaScript::Converter::toJSValueRef; +public: + explicit ContactConverter(JSContextRef context); + virtual ~ContactConverter(); + + TizenApis::Api::Contact::StringArrayPtr toStringArray(const JSValueRef &value); + JSValueRef toJSValueRef(const TizenApis::Api::Contact::StringArrayPtr &arg); + + TizenApis::Api::Contact::ContactEmailAddressType toContactEmailAddressType(const std::string &arg); + std::string toContactEmailAddressTypeStr(TizenApis::Api::Contact::ContactEmailAddressType arg); + TizenApis::Api::Contact::ContactEmailAddressType toContactEmailAddressType(const JSValueRef &value); + JSValueRef toJSValueRef(TizenApis::Api::Contact::ContactEmailAddressType arg); + + TizenApis::Api::Contact::ContactPhoneNumberType toContactPhoneNumberType(const std::string &arg); + std::string toContactPhoneNumberTypeStr(TizenApis::Api::Contact::ContactPhoneNumberType arg); + TizenApis::Api::Contact::ContactPhoneNumberType toContactPhoneNumberType(const JSValueRef &value); + JSValueRef toJSValueRef(TizenApis::Api::Contact::ContactPhoneNumberType arg); + + TizenApis::Api::Contact::ContactAddressType toContactAddressType(const std::string &arg); + std::string toContactAddressTypeStr(TizenApis::Api::Contact::ContactAddressType arg); + TizenApis::Api::Contact::ContactAddressType toContactAddressType(const JSValueRef &value); + JSValueRef toJSValueRef(TizenApis::Api::Contact::ContactAddressType arg); + + TizenApis::Api::Contact::ContactWebSiteType toContactWebSiteType(const std::string &arg); + std::string toContactWebSiteTypeStr(TizenApis::Api::Contact::ContactWebSiteType arg); + TizenApis::Api::Contact::ContactWebSiteType toContactWebSiteType(const JSValueRef &value); + JSValueRef toJSValueRef(TizenApis::Api::Contact::ContactWebSiteType arg); + + TizenApis::Api::Contact::ContactCapabilityType toContactCapabilityType(const JSValueRef &value); +// JSValueRef toJSValueRef(TizenApis::Api::Contact::ContactCapabilityType arg); + +// JSValueRef toJSValueRef(const std::string &arg); + std::string toAttributesOfInterest(const JSValueRef &value); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::IAddressBookPtr &arg); + TizenApis::Api::Contact::IAddressBookPtr toAddressBook(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::IAddressBookArrayPtr &arg); + TizenApis::Api::Contact::IAddressBookArrayPtr toAddressBookArray(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactPtr &arg); + TizenApis::Api::Contact::ContactPtr toContact(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactArrayPtr &arg); + TizenApis::Api::Contact::ContactArrayPtr toContactArray(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactPropertiesPtr &arg); + TizenApis::Api::Contact::ContactPropertiesPtr toContactProperties(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactPropertiesArrayPtr &arg); + TizenApis::Api::Contact::ContactPropertiesArrayPtr toContactPropertiesArray(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactNamePtr &arg); + TizenApis::Api::Contact::ContactNamePtr toContactName(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactAccountPtr &arg); + TizenApis::Api::Contact::ContactAccountPtr toContactAccount(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactAnniversaryPtr &arg); + TizenApis::Api::Contact::ContactAnniversaryPtr toContactAnniversary(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactAnniversaryArrayPtr &arg); + TizenApis::Api::Contact::ContactAnniversaryArrayPtr toContactAnniversaryArray(const JSValueRef &jsValue); + + JSValueRef toJSValueRefAttributesOfInterestArray(const TizenApis::Api::Contact::AttributesOfInterestArrayPtr &arg); + TizenApis::Api::Contact::AttributesOfInterestArrayPtr toAttributesOfInterestArray(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactAddressPtr &arg); + TizenApis::Api::Contact::ContactAddressPtr toContactAddress(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactAddressArrayPtr &arg); + TizenApis::Api::Contact::ContactAddressArrayPtr toContactAddressArray(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactAddressTypeArrayPtr &arg); + TizenApis::Api::Contact::ContactAddressTypeArrayPtr toContactAddressTypeArray(const JSValueRef &jsValue); + +// JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactCapabilityTypeArrayPtr &arg); +// TizenApis::Api::Contact::ContactCapabilityTypeArrayPtr toContactCapabilityTypeArray(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactPhoneNumberPtr &arg); + TizenApis::Api::Contact::ContactPhoneNumberPtr toContactPhoneNumber(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactPhoneNumberArrayPtr &arg); + TizenApis::Api::Contact::ContactPhoneNumberArrayPtr toContactPhoneNumberArray(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactPhoneNumberTypeArrayPtr &arg); + TizenApis::Api::Contact::ContactPhoneNumberTypeArrayPtr toContactPhoneNumberTypeArray(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactEmailAddressPtr &arg); + TizenApis::Api::Contact::ContactEmailAddressPtr toContactEmailAddress(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactEmailAddressArrayPtr &arg); + TizenApis::Api::Contact::ContactEmailAddressArrayPtr toContactEmailAddressArray(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactEmailAddressTypeArrayPtr &arg); + TizenApis::Api::Contact::ContactEmailAddressTypeArrayPtr toContactEmailAddressTypeArray(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactOrganizationPtr &arg); + TizenApis::Api::Contact::ContactOrganizationPtr toContactOrganization(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactOrganizationArrayPtr &arg); + TizenApis::Api::Contact::ContactOrganizationArrayPtr toContactOrganizationArray(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactWebSitePtr &arg); + TizenApis::Api::Contact::ContactWebSitePtr toContactWebSite(const JSValueRef &jsValue); + + JSValueRef toJSValueRef(const TizenApis::Api::Contact::ContactWebSiteArrayPtr &arg); + TizenApis::Api::Contact::ContactWebSiteArrayPtr toContactWebSiteArray(const JSValueRef &jsValue); + +private: + bool initializeAllowedProperties(); + static std::vector m_allowedAddressBookProperties; + static std::vector m_allowedContactProperties; + static std::vector m_allowedContactPropertiesProperties; + static std::vector m_allowedContactNameProperties; + static std::vector m_allowedContactAccountProperties; + static std::vector m_allowedContactOrganizationProperties; + static std::vector m_allowedContactWebSiteProperties; + static std::vector m_allowedContactAnniversaryProperties; + static std::vector m_allowedContactAddressProperties; + static std::vector m_allowedContactPhoneNumberProperties; + static std::vector m_allowedContactEmailAddressProperties; +}; + +typedef WrtDeviceApis::CommonsJavaScript::ConverterFactory ContactConverterFactory; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_JS_CONTACT_CONVERTER_H_ diff --git a/src/standards/Tizen/Contact/ContactManagerController.cpp b/src/standards/Tizen/Contact/ContactManagerController.cpp new file mode 100755 index 0000000..9a00ce2 --- /dev/null +++ b/src/standards/Tizen/Contact/ContactManagerController.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactManagerController.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include "ContactConverter.h" +#include "ContactManagerController.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +ContactManagerController::ContactManagerController(JSContextRef context, IContactManagerPtr contactManager) : + EventContactManagerGetAddressBooksAnswerReceiver(ThreadEnum::NULL_THREAD), + ContactManagerPrivObject(context, contactManager) +{ +} + +ContactManagerController::~ContactManagerController() +{ +} + +void ContactManagerAsyncAnswerHandler::getAddressBooks(const EventContactManagerGetAddressBooksPtr &event) +{ + JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast(event->getPrivateData()); + if (!callbackManager) { + LogError("no callback manager"); + return; + } + + JSContextRef gContext = callbackManager->getContext(); + + JSValueRef error = NULL; + if (ExceptionCodes::None != event->getExceptionCode()) + { + switch (event->getExceptionCode()) + { + case ExceptionCodes::PlatformException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Internal error"); + break; + case ExceptionCodes::InvalidArgumentException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Invalid value error"); + break; + case ExceptionCodes::ConversionException: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Wrong argument"); + break; + default: + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Unknown error"); + break; + } + + callbackManager->callOnError(error); + return; + } + + Try { + if (!event->getResult()) + ThrowMsg(PlatformException, "No result."); + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(gContext); + IAddressBookArrayPtr addressBooks = event->getAddressBooks(); + + JSValueRef result = converter->toJSValueRef(addressBooks); + + callbackManager->callOnSuccess(result); + return; + } Catch(Exception) { + LogError("error during processing answer" << _rethrown_exception.GetMessage()); + error = JSTizenExceptionFactory::makeErrorObject(gContext, JSTizenException::UNKNOWN_ERROR, "Internal error"); + + callbackManager->callOnError(error); + return; + } +} + +void ContactManagerController::OnAnswerReceived(const EventContactManagerGetAddressBooksPtr &event) +{ + ContactManagerAsyncAnswerHandler::getAddressBooks(event); +} + +void ContactManagerGetAddressBooksPendingOperation::handleCallingCallbacks() +{ + ContactManagerAsyncAnswerHandler::getAddressBooks(DPL::StaticPointerCast(m_event)); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/ContactManagerController.h b/src/standards/Tizen/Contact/ContactManagerController.h new file mode 100755 index 0000000..de348f2 --- /dev/null +++ b/src/standards/Tizen/Contact/ContactManagerController.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file ContactManagerController.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_MANAGER_CONTROLLER_H_ +#define _TIZEN_CONTACT_MANAGER_CONTROLLER_H_ + +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject ContactManagerPrivObject; + +typedef WrtDeviceApis::Commons::EventAnswerReceiver EventContactManagerGetAddressBooksAnswerReceiver; + +class ContactManagerController : + public EventContactManagerGetAddressBooksAnswerReceiver, + public ContactManagerPrivObject +{ +private: + ContactManagerController(); + +protected: + void OnAnswerReceived(const TizenApis::Api::Contact::EventContactManagerGetAddressBooksPtr &event); + +public: + ContactManagerController(JSContextRef context, + TizenApis::Api::Contact::IContactManagerPtr contactManager); + virtual ~ContactManagerController(); +}; + +typedef DPL::SharedPtr ContactManagerControllerPtr; + +class ContactManagerGetAddressBooksPendingOperation : public WrtDeviceApis::CommonsJavaScript::IJSPendingOperationPrivateObject +{ +public: + ContactManagerGetAddressBooksPendingOperation( + DPL::SharedPtr &event) : + WrtDeviceApis::CommonsJavaScript::IJSPendingOperationPrivateObject(event) + { + } + virtual void handleCallingCallbacks(); +}; + +//common part +class ContactManagerAsyncAnswerHandler +{ +public: + static void getAddressBooks(const TizenApis::Api::Contact::EventContactManagerGetAddressBooksPtr &event); +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_MANAGER_CONTROLLER_H_ diff --git a/src/standards/Tizen/Contact/JSAddressBook.cpp b/src/standards/Tizen/Contact/JSAddressBook.cpp new file mode 100755 index 0000000..af966d9 --- /dev/null +++ b/src/standards/Tizen/Contact/JSAddressBook.cpp @@ -0,0 +1,1075 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSAddressBook.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSAddressBook class + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "plugin_config.h" +#include "JSAddressBook.h" +#include "JSContact.h" +#include "ContactConverter.h" +#include "AddressBookController.h" +#include "JSAddressBookChangeCallbackManager.h" + +using namespace std; + +#define TIZEN_ADDRESS_BOOK_TYPE "type" +#define TIZEN_ADDRESS_BOOK_NAME "name" + +#define TIZEN_ADDRESS_BOOK "AddressBook" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; +using namespace TizenApis::Api::Tizen; +using namespace TizenApis::Tizen1_0::Tizen; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +using TizenApis::Api::Contact::Contact; + +JSClassRef JSAddressBook::m_jsClassRef = NULL; + +JSClassDefinition JSAddressBook::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_ADDRESS_BOOK, + 0, + m_property, + m_function, + Initialize, + Finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSAddressBook::m_property[] = { + { TIZEN_ADDRESS_BOOK_TYPE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_ADDRESS_BOOK_NAME, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSAddressBook::m_function[] = { + { "convertFromString", convertFromString, kJSPropertyAttributeNone }, + { "convertToString", convertToString, kJSPropertyAttributeNone }, + { "add", add, kJSPropertyAttributeNone }, + { "addBatch", addBatch, kJSPropertyAttributeNone }, + { "update", update, kJSPropertyAttributeNone }, + { "updateBatch", updateBatch, kJSPropertyAttributeNone }, + { "remove", remove, kJSPropertyAttributeNone }, + { "removeBatch", removeBatch, kJSPropertyAttributeNone }, + { "find", find, kJSPropertyAttributeNone }, + { "addChangeListener", addChangeListener, kJSPropertyAttributeNone }, + { "removeChangeListener", removeChangeListener, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassDefinition* JSAddressBook::getClassInfo() +{ + return &m_classInfo; +} + +const JSClassRef JSAddressBook::getClassRef() +{ + LogInfo("entered"); + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +void JSAddressBook::Initialize(JSContextRef context, + JSObjectRef object) +{ + ////LogDebug("entered"); + AddressBookController *priv = + static_cast(JSObjectGetPrivate(object)); + Assert(priv && "Private object not set."); +} + +void JSAddressBook::Finalize(JSObjectRef object) +{ + //LogDebug("entered"); +} + +bool JSAddressBook::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +IAddressBookPtr JSAddressBook::getAddressBook(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(InvalidArgumentException); + } + AddressBookController *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + return priv->getObject(); +} + +IAddressBookPtr JSAddressBook::getPrivData(JSObjectRef object) +{ + AddressBookController *priv = + static_cast(JSObjectGetPrivate(object)); + if (priv) { + return priv->getObject(); + } + Throw(NullPointerException); +} + +JSValueRef JSAddressBook::convertFromString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + IAddressBookPtr addressBook; + JSContextRef gContext; + AddressBookController *controller; + + Try { + controller = static_cast(JSObjectGetPrivate(thisObject)); + if (!controller) { + ThrowMsg(InvalidArgumentException, "No private object."); + } + addressBook = controller->getObject(); + gContext = controller->getContext(); + } Catch(Exception) { + LogError("No private object"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong object"); + } + + AceSecurityStatus status = CONTACT_CHECK_ACCESS(controller->getContext(), CONTACT_FUNCTION_API_CONVERT_FROM_STRING); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + BasicValidator validator = BasicValidatorFactory::getValidator(context, exception); + Try { + if (argumentCount != 2) + ThrowMsg(InvalidArgumentException, "Wrong arguments count."); + + if (!JSValueIsString(context, arguments[0])) + ThrowMsg(InvalidArgumentException, "1st argument is not string."); + + if (!JSValueIsString(context, arguments[1])) + ThrowMsg(InvalidArgumentException, "2nd argument is not string."); + } Catch(Exception ) { + LogError("Argument type mismatch : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + string vCardStr; + string format; + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + Try + { + vCardStr = converter->toString(arguments[0]); + format = converter->toString(arguments[1]); + } + Catch(Exception) { + LogError("Error on conversion " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + ContactPropertiesPtr contactProperties; + Try { + contactProperties = addressBook->convertFromString(vCardStr, format); + } Catch(UnsupportedException) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::NOT_SUPPORTED_ERROR, "Unsupported format"); + } Catch(Exception) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + JSValueRef result; + Try { + result = converter->toJSValueRef(contactProperties); + } Catch(Exception) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + return result; +} + +JSValueRef JSAddressBook::convertToString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + IAddressBookPtr addressBook; + JSContextRef gContext; + AddressBookController *controller; + + Try { + controller = static_cast(JSObjectGetPrivate(thisObject)); + if (!controller) { + ThrowMsg(InvalidArgumentException, "No private object."); + } + addressBook = controller->getObject(); + gContext = controller->getContext(); + } Catch(Exception) { + LogError("No private object"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong object"); + } + + AceSecurityStatus status = CONTACT_CHECK_ACCESS(controller->getContext(), CONTACT_FUNCTION_API_CONVERT_TO_STRING); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + BasicValidator validator = BasicValidatorFactory::getValidator(context, exception); + Try { + if (argumentCount != 2) + ThrowMsg(InvalidArgumentException, "Wrong arguments count."); + + if (!JSContact::isObjectOfClass(context, arguments[0])) + ThrowMsg(InvalidArgumentException, "1st argument is not contact object."); + + if (!JSValueIsString(context, arguments[1])) + ThrowMsg(InvalidArgumentException, "2nd argument is not string."); + } Catch(Exception ) { + LogError("Argument type mismatch : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + ContactPtr contact; + string format; + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + Try { + contact = converter->toContact(arguments[0]); + format = converter->toString(arguments[1]); + } Catch(Exception) { + LogError("Error on conversion : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + string vCard; + Try { + vCard = addressBook->convertToString(contact, format); + } Catch(UnsupportedException) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::NOT_SUPPORTED_ERROR, "Unsupported format"); + } Catch(Exception) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + JSValueRef result; + Try { + result = converter->toJSValueRef(vCard); + } Catch(Exception) { + LogError("Error on conversion : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + return result; +} + +JSValueRef JSAddressBook::add(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + IAddressBookPtr addressBook; + JSContextRef gContext; + AddressBookController *controller; + + Try { + controller = static_cast(JSObjectGetPrivate(thisObject)); + if (!controller) { + ThrowMsg(InvalidArgumentException, "No private object."); + } + addressBook = controller->getObject(); + gContext = controller->getContext(); + } Catch(Exception) { + LogError("No private object"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong object"); + } + + AceSecurityStatus status = CONTACT_CHECK_ACCESS(controller->getContext(), CONTACT_FUNCTION_API_ADD); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + BasicValidator validator = BasicValidatorFactory::getValidator(context, exception); + Try { + if (argumentCount != 1) + ThrowMsg(InvalidArgumentException, "Wrong arguments count."); + + if (!JSValueIsObject(context, arguments[0])) + ThrowMsg(InvalidArgumentException, "1st argument is not object."); + + } Catch(Exception ) { + LogError("Argument type mismatch : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + ContactPropertiesPtr contactProperties; + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + Try { + contactProperties = converter->toContactProperties(arguments[0]); + } Catch(Exception) { + LogError("Error on conversion : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + ContactPtr contact(NULL); + Try { + contact = addressBook->add(contactProperties); + } Catch(Exception) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + JSValueRef result; + Try { + result = converter->toJSValueRef(contact); + } Catch(Exception) { + LogError("Error on conversion : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + return result; +} + +JSValueRef JSAddressBook::addBatch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + IAddressBookPtr addressBook; + JSContextRef gContext; + AddressBookController *controller; + + Try { + controller = static_cast(JSObjectGetPrivate(thisObject)); + if (!controller) { + ThrowMsg(InvalidArgumentException, "No private object."); + } + addressBook = controller->getObject(); + gContext = controller->getContext(); + } Catch(Exception) { + LogError("No private object"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong object"); + } + + AceSecurityStatus status = CONTACT_CHECK_ACCESS(controller->getContext(), CONTACT_FUNCTION_API_ADD_BATCH); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + BasicValidator validator = BasicValidatorFactory::getValidator(context, exception); + Try { + if (argumentCount < 1 || argumentCount > 3) + ThrowMsg(InvalidArgumentException, "Wrong arguments count."); + + if (!JSIsArrayValue(context, arguments[0])) + ThrowMsg(InvalidArgumentException, "1st argument is not array."); + + if (argumentCount >= 2) + { + if (!validator->isCallback(arguments[1])) + ThrowMsg(InvalidArgumentException, "2nd argument is not function."); + } + + if (argumentCount >= 3) + { + if (!validator->isCallback(arguments[2])) + ThrowMsg(InvalidArgumentException, "3rd argument is not function."); + } + + } Catch(Exception ) { + LogError("Argument type mismatch : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + + if(argumentCount >= 2) + callbackManager->setOnSuccess(arguments[1]); + + if(argumentCount >= 3) + callbackManager->setOnError(arguments[2]); + + EventAddressBookAddBatchPtr dplEvent(new EventAddressBookAddBatch()); + Try { + dplEvent->setContactProperties(converter->toContactPropertiesArray(arguments[0])); + } Catch(ConversionException) { + LogError("Error on conversion : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + // set event handler's data + dplEvent->setPrivateData(DPL::StaticPointerCast(callbackManager)); + dplEvent->setForAsynchronousCall(controller); + + //DPL::SharedPtr eventContr = DPL::StaticPointerCast< IEventController>(dplEvent); + //AddressBookAddBatchPendingOperation *gcPendingOperation = new AddressBookAddBatchPendingOperation(eventContr); + + Try { + addressBook->addBatch(dplEvent); + } Catch(Exception) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + //return JSObjectMake(gContext, JSPendingOperation::getClassRef(), gcPendingOperation); + return JSValueMakeUndefined(context); +} + +JSValueRef JSAddressBook::update(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + IAddressBookPtr addressBook; + JSContextRef gContext; + AddressBookController *controller; + + Try { + controller = static_cast(JSObjectGetPrivate(thisObject)); + if (!controller) { + ThrowMsg(InvalidArgumentException, "No private object."); + } + addressBook = controller->getObject(); + gContext = controller->getContext(); + } Catch(Exception) { + LogError("No private object"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong object"); + } + + AceSecurityStatus status = CONTACT_CHECK_ACCESS(controller->getContext(), CONTACT_FUNCTION_API_UPDATE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + BasicValidator validator = BasicValidatorFactory::getValidator(context, exception); + Try { + if (argumentCount != 1) + ThrowMsg(InvalidArgumentException, "Wrong arguments count."); + + if (!JSContact::isObjectOfClass(context, arguments[0])) + ThrowMsg(InvalidArgumentException, "1st argument is wrong object."); + } Catch(Exception ) { + LogError("Argument type mismatch : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + ContactPtr contact; + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + Try { + contact = converter->toContact(arguments[0]); + } Catch(Exception) { + LogError("Error on conversion : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + Try { + addressBook->update(contact); + } Catch(Exception) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + JSValueRef result = JSValueMakeUndefined(context); + + return result; +} + +JSValueRef JSAddressBook::updateBatch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + IAddressBookPtr addressBook; + JSContextRef gContext; + AddressBookController *controller; + + Try { + controller = static_cast(JSObjectGetPrivate(thisObject)); + if (!controller) { + ThrowMsg(InvalidArgumentException, "No private object."); + } + addressBook = controller->getObject(); + gContext = controller->getContext(); + } Catch(Exception) { + LogError("No private object"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong object"); + } + + AceSecurityStatus status = CONTACT_CHECK_ACCESS(controller->getContext(), CONTACT_FUNCTION_API_UPDATE_BATCH); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + BasicValidator validator = BasicValidatorFactory::getValidator(context, exception); + Try { + if (argumentCount < 1 || argumentCount > 3) + ThrowMsg(InvalidArgumentException, "Wrong arguments count."); + + if (!JSIsArrayValue(context, arguments[0])) + ThrowMsg(InvalidArgumentException, "1st argument is not array."); + + if (argumentCount >= 2) + { + if (!validator->isCallback(arguments[1])) + ThrowMsg(InvalidArgumentException, "2nd argument is not function."); + } + + if (argumentCount >= 3) + { + if (!validator->isCallback(arguments[2])) + ThrowMsg(InvalidArgumentException, "3rd argument is not function."); + } + } Catch(Exception ) { + LogError("Argument type mismatch : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + + if(argumentCount >= 2) + callbackManager->setOnSuccess(arguments[1]); + + if(argumentCount >= 3) + callbackManager->setOnError(arguments[2]); + + EventAddressBookUpdateBatchPtr dplEvent(new EventAddressBookUpdateBatch()); + Try { + dplEvent->setContacts(converter->toContactArray(arguments[0])); + } Catch(ConversionException) { + LogError("Error on conversion : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + // set event handler's data + dplEvent->setPrivateData(DPL::StaticPointerCast(callbackManager)); + dplEvent->setForAsynchronousCall(controller); + + //DPL::SharedPtr eventContr = DPL::StaticPointerCast< IEventController>(dplEvent); + //AddressBookUpdateBatchPendingOperation *gcPendingOperation = new AddressBookUpdateBatchPendingOperation(eventContr); + + Try { + addressBook->updateBatch(dplEvent); + } Catch(Exception) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + //return JSObjectMake(gContext, JSPendingOperation::getClassRef(), gcPendingOperation); + return JSValueMakeUndefined(context); +} + +JSValueRef JSAddressBook::remove(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + IAddressBookPtr addressBook; + JSContextRef gContext; + AddressBookController *controller; + + Try { + controller = static_cast(JSObjectGetPrivate(thisObject)); + if (!controller) { + ThrowMsg(InvalidArgumentException, "No private object."); + } + addressBook = controller->getObject(); + gContext = controller->getContext(); + } Catch(Exception) { + LogError("No private object"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong object"); + } + + AceSecurityStatus status = CONTACT_CHECK_ACCESS(controller->getContext(), CONTACT_FUNCTION_API_REMOVE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + BasicValidator validator = BasicValidatorFactory::getValidator(context, exception); + Try { + if (argumentCount != 1) + ThrowMsg(InvalidArgumentException, "Wrong arguments count."); + + if (!JSValueIsString(context, arguments[0])) + ThrowMsg(InvalidArgumentException, "1st argument is wrong object."); + } Catch(Exception ) { + LogError("Argument type mismatch : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + string contactId; + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + Try { + contactId = converter->toString(arguments[0]); + } Catch(Exception) { + LogError("Error on conversion : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + Try { + addressBook->remove(contactId); + } Catch(NotFoundException) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::NOT_FOUND_ERROR, "Contact id not found"); + } Catch(Exception) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + JSValueRef result = JSValueMakeUndefined(context); + + return result; +} + +JSValueRef JSAddressBook::removeBatch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + IAddressBookPtr addressBook; + JSContextRef gContext; + AddressBookController *controller; + + Try { + controller = static_cast(JSObjectGetPrivate(thisObject)); + if (!controller) { + ThrowMsg(InvalidArgumentException, "No private object."); + } + addressBook = controller->getObject(); + gContext = controller->getContext(); + } Catch(Exception) { + LogError("No private object"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong object"); + } + + AceSecurityStatus status = CONTACT_CHECK_ACCESS(controller->getContext(), CONTACT_FUNCTION_API_REMOVE_BATCH); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + BasicValidator validator = BasicValidatorFactory::getValidator(context, exception); + Try { + if (argumentCount < 1 || argumentCount > 3) + ThrowMsg(InvalidArgumentException, "Wrong arguments count."); + + if (!JSIsArrayValue(context, arguments[0])) + ThrowMsg(InvalidArgumentException, "1st argument is not array."); + + if (argumentCount >= 2) + { + if (!validator->isCallback(arguments[1])) + ThrowMsg(InvalidArgumentException, "2nd argument is not function."); + } + + if (argumentCount >= 3) + { + if (!validator->isCallback(arguments[2])) + ThrowMsg(InvalidArgumentException, "3rd argument is not function."); + } + } Catch(Exception ) { + LogError("Argument type mismatch : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + + if(argumentCount >= 2) + callbackManager->setOnSuccess(arguments[1]); + + if(argumentCount >= 3) + callbackManager->setOnError(arguments[2]); + + EventAddressBookRemoveBatchPtr dplEvent(new EventAddressBookRemoveBatch()); + Try { + dplEvent->setContactIds(converter->toStringArray(arguments[0])); + } Catch(ConversionException) { + LogError("Error on conversion : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + // set event handler's data + dplEvent->setPrivateData(DPL::StaticPointerCast(callbackManager)); + dplEvent->setForAsynchronousCall(controller); + + //DPL::SharedPtr eventContr = DPL::StaticPointerCast< IEventController>(dplEvent); + //AddressBookRemoveBatchPendingOperation *gcPendingOperation = new AddressBookRemoveBatchPendingOperation(eventContr); + + Try { + addressBook->removeBatch(dplEvent); + } Catch(Exception) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + //return JSObjectMake(gContext, JSPendingOperation::getClassRef(), gcPendingOperation); + return JSValueMakeUndefined(context); +} + +JSValueRef JSAddressBook::find(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + IAddressBookPtr addressBook; + JSContextRef gContext; + AddressBookController *controller; + + Try { + controller = static_cast(JSObjectGetPrivate(thisObject)); + if (!controller) { + ThrowMsg(InvalidArgumentException, "No private object."); + } + addressBook = controller->getObject(); + gContext = controller->getContext(); + } Catch(Exception) { + LogError("No private object"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong object"); + } + + AceSecurityStatus status = CONTACT_CHECK_ACCESS(controller->getContext(), CONTACT_FUNCTION_API_FIND); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + BasicValidator validator = BasicValidatorFactory::getValidator(context, exception); + Try { + if (argumentCount < 1 || argumentCount > 4) + ThrowMsg(InvalidArgumentException, "Wrong arguments count."); + + if (!validator->isCallback(arguments[0])) + ThrowMsg(InvalidArgumentException, "1st argument is not function."); + + if (argumentCount >= 2) + { + if (!validator->isCallback(arguments[1])) + ThrowMsg(InvalidArgumentException, "2nd argument is not function."); + } + + if (argumentCount >= 3) + { + if (!JSValueIsObject(context, arguments[2]) && !JSValueIsNull(context, arguments[2])) + ThrowMsg(InvalidArgumentException, "3rd argument is not object nor null."); + } + + if (argumentCount >= 4) + { + if (!JSValueIsObject(context, arguments[3]) && !JSValueIsNull(context, arguments[3])) + ThrowMsg(InvalidArgumentException, "4th argument is not object nor null."); + } + } Catch(Exception ) { + LogError("Argument type mismatch : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + + callbackManager->setOnSuccess(arguments[0]); + if (argumentCount >= 2) + callbackManager->setOnError(arguments[1]); + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + FilterConverterFactory::ConverterType filterConverter = FilterConverterFactory::getConverter(context); + + EventAddressBookFindPtr dplEvent(new EventAddressBookFind()); + Try { + if (argumentCount >= 3 && !JSValueIsNull(context, arguments[2])) + dplEvent->setFilter(filterConverter->toFilter(arguments[2])); + + if (argumentCount >= 4 && !JSValueIsNull(context, arguments[3])) + dplEvent->setSortModes(filterConverter->toSortModeArray(arguments[3])); + } Catch(Exception) { + LogError("Error on conversion : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + // set event handler's data + dplEvent->setPrivateData(DPL::StaticPointerCast(callbackManager)); + dplEvent->setForAsynchronousCall(controller); + + //DPL::SharedPtr eventContr = DPL::StaticPointerCast< IEventController>(dplEvent); + //AddressBookFindPendingOperation *gcPendingOperation = new AddressBookFindPendingOperation(eventContr); + + Try { + addressBook->find(dplEvent); + } Catch(Exception) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + //return JSObjectMake(gContext, JSPendingOperation::getClassRef(), gcPendingOperation); + return JSValueMakeUndefined(context); +} + +JSValueRef JSAddressBook::addChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + IAddressBookPtr addressBook; + JSContextRef gContext; + AddressBookController *controller; + + Try { + controller = static_cast(JSObjectGetPrivate(thisObject)); + if (!controller) { + ThrowMsg(InvalidArgumentException, "No private object."); + } + addressBook = controller->getObject(); + gContext = controller->getContext(); + } Catch(Exception) { + LogError("No private object"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Wrong object"); + } + + AceSecurityStatus status = CONTACT_CHECK_ACCESS(controller->getContext(), CONTACT_FUNCTION_API_ADD_CHANGE_LISTENER); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + BasicValidator validator = BasicValidatorFactory::getValidator(context, exception); + Try { + if (argumentCount < 1 || argumentCount > 2) + ThrowMsg(InvalidArgumentException, "Wrong arguments count."); + + if (!JSValueIsObject(context, arguments[0])) + ThrowMsg(InvalidArgumentException, "1st argument is not object."); + + if (argumentCount >= 2) + { + if (!validator->isCallback(arguments[1])) + ThrowMsg(InvalidArgumentException, "2nd argument is not function."); + } + } Catch(Exception ) { + LogError("Argument type mismatch : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + + JSValueRef oncontactsadded; + JSValueRef oncontactsupdated; + JSValueRef oncontactsdeleted; + JSValueRef onaddressbookreset; + Try { + JSObjectRef callbackObject = converter->toJSObjectRef(arguments[0]); + + oncontactsadded = JSUtils::getJSPropertyOrUndefined(context, callbackObject, "onContactsAdded"); + if (validator->isNullOrUndefined(oncontactsadded)) + oncontactsadded = NULL; + else if (!validator->isCallback(oncontactsadded)) { + ThrowMsg(ConversionException, "Not a valid callback (onContactsAdded)"); + } + + oncontactsupdated = JSUtils::getJSPropertyOrUndefined(context, callbackObject, "onContactsUpdated"); + if (validator->isNullOrUndefined(oncontactsupdated)) + oncontactsupdated = NULL; + else if (!validator->isCallback(oncontactsupdated)) { + ThrowMsg(ConversionException, "Not a valid callback (onContactsUpdated)"); + } + + oncontactsdeleted = JSUtils::getJSPropertyOrUndefined(context, callbackObject, "onContactsRemoved"); + if (validator->isNullOrUndefined(oncontactsdeleted)) + oncontactsdeleted = NULL; + else if (!validator->isCallback(oncontactsdeleted)) { + ThrowMsg(ConversionException, "Not a valid callback (onContactsRemoved)"); + } + + onaddressbookreset = JSUtils::getJSPropertyOrUndefined(context, callbackObject, "onAddressBookReset"); + if (validator->isNullOrUndefined(onaddressbookreset)) + onaddressbookreset = NULL; + else if (!validator->isCallback(onaddressbookreset)) { + ThrowMsg(ConversionException, "Not a valid callback (onAddressBookReset)"); + } + } Catch(ConversionException) { + LogError("Error on conversion : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + JSAddressBookChangeCallbackManagerPtr callbackManager = JSAddressBookChangeCallbackManager::createObject(gContext); + + callbackManager->setOnContactsAdded(oncontactsadded); + callbackManager->setOnContactsUpdated(oncontactsupdated); + callbackManager->setOnContactsDeleted(oncontactsdeleted); + callbackManager->setOnAddressBookReset(onaddressbookreset); + if(argumentCount >= 2) + callbackManager->setOnError(arguments[1]); + + EventAddressBookChangeListenerEmitterPtr emitter(new EventAddressBookChangeListenerEmitter()); + + emitter->setEventPrivateData(DPL::StaticPointerCast(callbackManager)); + emitter->setListener(controller); + + long watchId; + Try { + watchId = addressBook->addChangeListener(emitter); + } Catch(Exception) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + return converter->toJSValueRefLong(watchId); +} + +JSValueRef JSAddressBook::removeChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + IAddressBookPtr addressBook; + JSContextRef gContext; + AddressBookController *controller; + + Try { + controller = static_cast(JSObjectGetPrivate(thisObject)); + if (!controller) { + ThrowMsg(InvalidArgumentException, "No private object."); + } + addressBook = controller->getObject(); + gContext = controller->getContext(); + } Catch(Exception) { + LogError("No private object"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Wrong object"); + } + + AceSecurityStatus status = CONTACT_CHECK_ACCESS(controller->getContext(), CONTACT_FUNCTION_API_REMOVE_CHANGE_LISTENER); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + BasicValidator validator = BasicValidatorFactory::getValidator(context, exception); + Try { + if (argumentCount != 1) + ThrowMsg(InvalidArgumentException, "Wrong arguments count."); + + if (!JSValueIsNumber(context, arguments[0])) + ThrowMsg(InvalidArgumentException, "1st argument is not object."); + } Catch(Exception ) { + LogError("Argument type mismatch : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + + long watchId; + Try { + watchId = static_cast(converter->toLong(arguments[0])); + + if (watchId < 0) + ThrowMsg(PlatformException, "watchId is wrong (" << watchId << ")"); + + addressBook->removeChangeListener(watchId); + } Catch(Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSAddressBook::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef jsPropertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + Try + { + std::string propertyName = converter->toString(jsPropertyName); + IAddressBookPtr addressBook = getPrivData(object); + if (propertyName == TIZEN_ADDRESS_BOOK_TYPE) { + if (IAddressBook::SIMBook == addressBook->getType()) { + return converter->toJSValueRef(0); + } else { + return converter->toJSValueRef(1); + } + } else if (propertyName == TIZEN_ADDRESS_BOOK_NAME) { + return converter->toJSValueRef(addressBook->getName()); + } + } + Catch(Exception) + { + LogError("error during getting property"); + } + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSAddressBook.h b/src/standards/Tizen/Contact/JSAddressBook.h new file mode 100755 index 0000000..0971fe3 --- /dev/null +++ b/src/standards/Tizen/Contact/JSAddressBook.h @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSAddressBook.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSAddressBook class + */ + +#ifndef _TIZEN_CONTACT_JS_ADDRESS_BOOK_H_ +#define _TIZEN_CONTACT_JS_ADDRESS_BOOK_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject + JSAddressBookPriv; + +class JSAddressBook +{ +public: + + static const JSClassRef getClassRef(); + + static const JSClassDefinition* getClassInfo(); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::IAddressBookPtr getAddressBook(JSContextRef context, JSValueRef value); + +private: + /** + * The callback invoked when an object is first created. + */ + static void Initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void Finalize(JSObjectRef object); + + /** + * Getter for all properties + */ + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef jsPropertyName, + JSValueRef* exception); + + static JSClassDefinition m_classInfo; + + static JSStaticFunction m_function[]; + + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + static TizenApis::Api::Contact::IAddressBookPtr getPrivData(JSObjectRef object); + + static JSValueRef convertFromString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef convertToString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef add(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef addBatch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef update(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef updateBatch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef remove(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef removeBatch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef find(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef addChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef removeChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_ADDRESS_BOOK_H_ diff --git a/src/standards/Tizen/Contact/JSAddressBookArray.cpp b/src/standards/Tizen/Contact/JSAddressBookArray.cpp new file mode 100755 index 0000000..3bbe48d --- /dev/null +++ b/src/standards/Tizen/Contact/JSAddressBookArray.cpp @@ -0,0 +1,589 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSAddressBookArray.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSAddressBookArray.h" + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassDefinition JSAddressBookArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSAddressBookArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSAddressBookArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSAddressBookArray::m_jsClassRef = JSClassCreate( + JSAddressBookArray::getClassInfo()); + +JSValueRef JSAddressBookArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + JSAddressBookArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + IAddressBookArrayPtr addressBooks = priv->getObject(); + if (addressBooks) { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + return converter->toJSValueRef(addressBooks->size()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSAddressBookArray::createArray(JSContextRef context, + const IAddressBookArrayPtr &addressBooks) +{ + JSAddressBookArrayPriv *priv = new JSAddressBookArrayPriv(context, addressBooks); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSAddressBookArray::getClassInfo() +{ + return &(m_classInfo); +} + +bool JSAddressBookArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +IAddressBookArrayPtr JSAddressBookArray::getAddressBookArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSAddressBookArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +JSClassRef JSAddressBookArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +void JSAddressBookArray::initialize(JSContextRef context, + JSObjectRef object) +{ + //LogDebug("enter"); +} + +void JSAddressBookArray::finalize(JSObjectRef object) +{ + //LogDebug("enter"); + JSAddressBookArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSAddressBookArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSAddressBookArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + IAddressBookArrayPtr addressBooks = priv->getObject(); + if (index < addressBooks->size()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSAddressBookArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSAddressBookArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + IAddressBookArrayPtr addressBooks = priv->getObject(); + if (index < addressBooks->size()) { + IAddressBookPtr result = addressBooks->at(index); + if (result) { + return converter->toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSAddressBookArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + IAddressBookPtr addressBook; + if (!JSValueIsUndefined(context, value)) { + addressBook = converter->toAddressBook(value); + } + JSAddressBookArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + IAddressBookArrayPtr addressBooks = priv->getObject(); + if (!addressBooks) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (addressBooks->size() <= index) { + addressBooks->resize(index + 1); + } + (*addressBooks)[index] = addressBook; + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + } + return false; +} + +JSValueRef JSAddressBookArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + IAddressBookArrayPtr addressBooks = IAddressBookArrayPtr(new IAddressBookArray()); + JSAddressBookArrayPriv *newPrivateObject = new JSAddressBookArrayPriv(context, addressBooks); + JSValueRef result = JSObjectMake(context, getClassRef(), newPrivateObject); + + //copy current addressBooks + JSAddressBookArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + IAddressBookArrayPtr currentAddressBooks = priv->getObject(); + for (size_t i = 0; i < currentAddressBooks->size(); ++i) { + addressBooks->push_back(currentAddressBooks->at(i)); + } + + //copy submitted arrays + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + addressBooks->push_back(converter->toAddressBook(att)); + } + } + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSAddressBookArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSAddressBookArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + IAddressBookArrayPtr currentAddressBooks = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentAddressBooks->size(); ++i) { + if (i != 0) { + result += separator; + } + //FIXME : to be changed to support join + //result += currentAddressBooks->at(i); + } + return converter->toJSValueRef(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSAddressBookArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSAddressBookArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + IAddressBookArrayPtr currentAddressBooks = priv->getObject(); + if (currentAddressBooks->size() > 0) { + IAddressBookPtr result = currentAddressBooks->at( + currentAddressBooks->size() - 1); + currentAddressBooks->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSAddressBookArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSAddressBookArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + IAddressBookArrayPtr currentAddressBooks = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentAddressBooks->push_back(converter->toAddressBook(arguments[i])); + } + return converter->toJSValueRef(currentAddressBooks->size()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSAddressBookArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSAddressBookArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + IAddressBookArrayPtr currentAddressBooks = priv->getObject(); + std::reverse(currentAddressBooks->begin(), currentAddressBooks->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSAddressBookArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSAddressBookArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + IAddressBookArrayPtr currentAddressBooks = priv->getObject(); + if (currentAddressBooks->size() > 0) { + IAddressBookPtr result = currentAddressBooks->at(0); + currentAddressBooks->erase(currentAddressBooks->begin()); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSAddressBookArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + IAddressBookArrayPtr addressBooks = IAddressBookArrayPtr(new IAddressBookArray()); + JSAddressBookArrayPriv *newPrivateObject = new JSAddressBookArrayPriv( + context, + addressBooks); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current addressBooks + JSAddressBookArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + IAddressBookArrayPtr currentAddressBooks = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentAddressBooks->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentAddressBooks->size()) { + last = currentAddressBooks->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + addressBooks->push_back(currentAddressBooks->at(i)); + } + + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSAddressBookArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSAddressBookArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + IAddressBookArrayPtr currentAddressBooks = priv->getObject(); + std::sort(currentAddressBooks->begin(), currentAddressBooks->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSAddressBookArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSAddressBookArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSAddressBookArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSAddressBookArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSAddressBookArray.h b/src/standards/Tizen/Contact/JSAddressBookArray.h new file mode 100755 index 0000000..3c635b9 --- /dev/null +++ b/src/standards/Tizen/Contact/JSAddressBookArray.h @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSAddressBookArray.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_ADDRESS_BOOK_ARRAY_H_ +#define _TIZEN_CONTACT_JS_ADDRESS_BOOK_ARRAY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSAddressBookArrayPriv; + +class JSAddressBookArray +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const TizenApis::Api::Contact::IAddressBookArrayPtr &anniversaries); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::IAddressBookArrayPtr getAddressBookArray(JSContextRef context, JSValueRef value); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_ADDRESS_BOOK_ARRAY_H_ diff --git a/src/standards/Tizen/Contact/JSAddressBookChangeCallbackManager.cpp b/src/standards/Tizen/Contact/JSAddressBookChangeCallbackManager.cpp new file mode 100755 index 0000000..e3477ed --- /dev/null +++ b/src/standards/Tizen/Contact/JSAddressBookChangeCallbackManager.cpp @@ -0,0 +1,321 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSAddressBookChangeCallbackManager.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "JSAddressBookChangeCallbackManager.h" +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +JSAddressBookChangeCallbackManagerPtr JSAddressBookChangeCallbackManager::createObject(JSContextRef context) +{ + ////LogDebug("entered"); + + return JSAddressBookChangeCallbackManagerPtr( new JSAddressBookChangeCallbackManager(context) ); +} + +JSAddressBookChangeCallbackManager::JSAddressBookChangeCallbackManager(JSContextRef context, + JSObjectRef onContactsAdded, + JSObjectRef onContactsUpdated, + JSObjectRef onContactsDeleted, + JSObjectRef onAddressBookReset, + JSObjectRef onError ) : + m_onContactsAdded(NULL), + m_onContactsUpdated(NULL), + m_onContactsDeleted(NULL), + m_onAddressBookReset(NULL), + m_onError(NULL), + m_context(context), + m_object(NULL) +{ + //LogDebug("entered"); + + setOnContactsAdded(onContactsAdded); + setOnContactsUpdated(onContactsUpdated); + setOnContactsDeleted(onContactsDeleted); + setOnAddressBookReset(onAddressBookReset); + setOnError(onError); +} + +JSAddressBookChangeCallbackManager::~JSAddressBookChangeCallbackManager() +{ + //LogDebug("entered"); + + if(m_onContactsAdded) + { + JSValueUnprotect(m_context, m_onContactsAdded); + } + + if(m_onContactsUpdated) + { + JSValueUnprotect(m_context, m_onContactsUpdated); + } + + if(m_onContactsDeleted) + { + JSValueUnprotect(m_context, m_onContactsDeleted); + } + + if(m_onAddressBookReset) + { + JSValueUnprotect(m_context, m_onAddressBookReset); + } + + if(m_onError) + { + JSValueUnprotect(m_context, m_onError); + } +} + +void JSAddressBookChangeCallbackManager::setOnContactsAdded( JSValueRef onContactsAdded ) +{ + //LogDebug("entered"); + if (onContactsAdded) + { + if (m_onContactsAdded != NULL) + { + JSValueUnprotect(m_context, m_onContactsAdded); + } + + m_onContactsAdded = JSValueToObject( m_context, onContactsAdded, NULL ); + + if (m_onContactsAdded != NULL) + { + JSValueProtect(m_context, m_onContactsAdded); + } + } +} + +JSValueRef JSAddressBookChangeCallbackManager::getOnContactsAdded() const +{ + //LogDebug("entered"); + return m_onContactsAdded; +} + +void JSAddressBookChangeCallbackManager::setOnContactsUpdated( JSValueRef onContactsUpdated ) +{ + //LogDebug("entered"); + if (onContactsUpdated) + { + if (m_onContactsUpdated != NULL) + { + JSValueUnprotect(m_context, m_onContactsUpdated); + } + + m_onContactsUpdated = JSValueToObject( m_context, onContactsUpdated, NULL ); + + if (m_onContactsUpdated != NULL) + { + JSValueProtect(m_context, m_onContactsUpdated); + } + } +} + +JSValueRef JSAddressBookChangeCallbackManager::getOnContactsUpdated() const +{ + //LogDebug("entered"); + return m_onContactsUpdated; +} + +void JSAddressBookChangeCallbackManager::setOnContactsDeleted( JSValueRef onContactsDeleted ) +{ + //LogDebug("entered"); + if (onContactsDeleted) + { + if (m_onContactsDeleted != NULL) + { + JSValueUnprotect(m_context, m_onContactsDeleted); + } + + m_onContactsDeleted = JSValueToObject( m_context, onContactsDeleted, NULL ); + + if (m_onContactsDeleted != NULL) + { + JSValueProtect(m_context, m_onContactsDeleted); + } + } +} + +JSValueRef JSAddressBookChangeCallbackManager::getOnContactsDeleted() const +{ + //LogDebug("entered"); + return m_onContactsDeleted; +} + +void JSAddressBookChangeCallbackManager::setOnAddressBookReset( JSValueRef onAddressBookReset ) +{ + //LogDebug("entered"); + if (onAddressBookReset) + { + if (m_onAddressBookReset != NULL) + { + JSValueUnprotect(m_context, m_onAddressBookReset); + } + + m_onAddressBookReset = JSValueToObject( m_context, onAddressBookReset, NULL ); + + if (m_onAddressBookReset != NULL) + { + JSValueProtect(m_context, m_onAddressBookReset); + } + } +} + +JSValueRef JSAddressBookChangeCallbackManager::getOnAddressBookReset() const +{ + //LogDebug("entered"); + return m_onAddressBookReset; +} + +void JSAddressBookChangeCallbackManager::setOnError( JSValueRef onError ) +{ + //LogDebug("entered"); + if (onError) + { + if (m_onError != NULL) + { + JSValueUnprotect(m_context, m_onError); + } + + m_onError = JSValueToObject( m_context, onError, NULL ); + + if (m_onError != NULL) + { + JSValueProtect(m_context, m_onError); + } + } +} + +JSValueRef JSAddressBookChangeCallbackManager::getOnError() const +{ + //LogDebug("entered"); + return m_onError; +} + +void JSAddressBookChangeCallbackManager::setContext( JSContextRef context ) +{ + //LogDebug("entered"); + m_context = context; +} + +void JSAddressBookChangeCallbackManager::setObject( JSObjectRef object ) +{ + //LogDebug("entered"); + m_object = object; +} + +JSObjectRef JSAddressBookChangeCallbackManager::getObject() const +{ + //LogDebug("entered"); + return m_object; +} + +void JSAddressBookChangeCallbackManager::callOnContactsAdded( JSValueRef contacts ) +{ + //LogDebug("entered"); + if ( m_onContactsAdded == NULL ) + { + //LogDebug("oncontactsadded callback is not set"); + return; + } + JSValueRef objParam[1] = { contacts }; + makeCallback( m_context, NULL, m_onContactsAdded, "oncontactsadded", objParam, 1 ); +} + +void JSAddressBookChangeCallbackManager::callOnContactsUpdated( JSValueRef contacts ) +{ + //LogDebug("entered"); + if ( m_onContactsUpdated == NULL ) + { + //LogDebug("oncontactsupdated callback is not set"); + return; + } + JSValueRef objParam[1] = { contacts }; + makeCallback( m_context, NULL, m_onContactsUpdated, "oncontactsupdated", objParam, 1 ); +} + +void JSAddressBookChangeCallbackManager::callOnContactsDeleted( JSValueRef contactIds ) +{ + //LogDebug("entered"); + if ( m_onContactsDeleted == NULL ) + { + //LogDebug("oncontactsdeleted callback is not set"); + return; + } + JSValueRef objParam[1] = { contactIds }; + makeCallback( m_context, NULL, m_onContactsDeleted, "oncontactsdeleted", objParam, 1 ); +} + +void JSAddressBookChangeCallbackManager::callOnAddressBookReset() +{ + //LogDebug("entered"); + if ( m_onAddressBookReset == NULL ) + { + //LogDebug("onaddressbookreset callback is not set"); + return; + } + makeCallback( m_context, NULL, m_onAddressBookReset, "onaddressbookreset", NULL, 0 ); +} + +void JSAddressBookChangeCallbackManager::callOnError( JSValueRef error ) +{ + //LogDebug("entered"); + if ( m_onError == NULL ) + { + //LogDebug("Error callback is not set"); + return; + } + JSValueRef objParam[1] = { error }; + makeCallback( m_context, NULL, m_onError, "onError", objParam, 1 ); +} + +void JSAddressBookChangeCallbackManager::makeCallback(JSContextRef context, JSObjectRef object, JSObjectRef callback, const char *szName, JSValueRef argv[], unsigned argc) +{ + //LogDebug("entered"); + + if (callback == NULL) + { + LogError("callback is NULL"); + return; + } + + if (JSObjectIsFunction(context, callback)) + { + if (argc == 0) + { + //LogDebug("Calling object directly, no arguments"); + JSObjectCallAsFunction(context, callback, object, 0, NULL, NULL); + } + else + { + //LogDebug("Calling object directly, one argument"); + JSObjectCallAsFunction(context, callback, object, argc, argv, NULL); + } + return; + } +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSAddressBookChangeCallbackManager.h b/src/standards/Tizen/Contact/JSAddressBookChangeCallbackManager.h new file mode 100755 index 0000000..3b5cbe2 --- /dev/null +++ b/src/standards/Tizen/Contact/JSAddressBookChangeCallbackManager.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSAddressBookChangeCallbackManager.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_ADDRESS_BOOK_CHANGE_CALLBACK_MANAGER_H_ +#define _TIZEN_CONTACT_JS_ADDRESS_BOOK_CHANGE_CALLBACK_MANAGER_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +class JSAddressBookChangeCallbackManager; +typedef DPL::SharedPtr JSAddressBookChangeCallbackManagerPtr; + +class JSAddressBookChangeCallbackManager : public WrtDeviceApis::Commons::IEventPrivateData +{ +private: + JSAddressBookChangeCallbackManager() {} + JSAddressBookChangeCallbackManager( JSContextRef context, + JSObjectRef onContactsAdded = NULL, + JSObjectRef onContactsUpdated = NULL, + JSObjectRef onContactsDeleted = NULL, + JSObjectRef onAddressBookReset = NULL, + JSObjectRef onError = NULL ); + +public: + static JSAddressBookChangeCallbackManagerPtr createObject(JSContextRef context); + + virtual ~JSAddressBookChangeCallbackManager(); + + void setContext( JSContextRef context ); + JSContextRef getContext() const { return m_context; } + + void setOnContactsAdded( JSValueRef onContactsAdded ); + JSValueRef getOnContactsAdded() const; + void setOnContactsUpdated( JSValueRef onContactsUpdated ); + JSValueRef getOnContactsUpdated() const; + void setOnContactsDeleted( JSValueRef onContactsDeleted ); + JSValueRef getOnContactsDeleted() const; + void setOnAddressBookReset( JSValueRef onAddressBookReset ); + JSValueRef getOnAddressBookReset() const; + void setOnError( JSValueRef onError ); + JSValueRef getOnError() const; + void setObject( JSObjectRef object ); + JSObjectRef getObject() const; + + void callOnContactsAdded( JSValueRef contacts ); + void callOnContactsUpdated( JSValueRef contacts ); + void callOnContactsDeleted( JSValueRef contactIds ); + void callOnAddressBookReset( ); + void callOnError( JSValueRef error ); + +private: + void makeCallback(JSContextRef context, + JSObjectRef object, + JSObjectRef callback, + const char *szName, + JSValueRef argv[], + unsigned argc); + + JSObjectRef m_onContactsAdded; + JSObjectRef m_onContactsUpdated; + JSObjectRef m_onContactsDeleted; + JSObjectRef m_onAddressBookReset; + JSObjectRef m_onError; + JSContextRef m_context; + JSObjectRef m_object; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_ADDRESS_BOOK_CHANGE_CALLBACK_MANAGER_H_ diff --git a/src/standards/Tizen/Contact/JSAttributesOfInterestArray.cpp b/src/standards/Tizen/Contact/JSAttributesOfInterestArray.cpp new file mode 100755 index 0000000..2002567 --- /dev/null +++ b/src/standards/Tizen/Contact/JSAttributesOfInterestArray.cpp @@ -0,0 +1,592 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSAttributesOfInterestArray.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSAttributesOfInterestArray.h" + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassDefinition JSAttributesOfInterestArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSAttributesOfInterestArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSAttributesOfInterestArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSAttributesOfInterestArray::m_jsClassRef = JSClassCreate( + JSAttributesOfInterestArray::getClassInfo()); + +JSValueRef JSAttributesOfInterestArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + JSAttributesOfInterestArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + AttributesOfInterestArrayPtr typeArray = priv->getObject(); + if (typeArray) { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + return converter->toJSValueRef(typeArray->size()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSAttributesOfInterestArray::createArray(JSContextRef context, + const AttributesOfInterestArrayPtr &typeArray) +{ + JSAttributesOfInterestArrayPriv *priv = new JSAttributesOfInterestArrayPriv(context, typeArray); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSAttributesOfInterestArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSAttributesOfInterestArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +bool JSAttributesOfInterestArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +AttributesOfInterestArrayPtr JSAttributesOfInterestArray::getAttributesOfInterestArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSAttributesOfInterestArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSAttributesOfInterestArray::initialize(JSContextRef context, + JSObjectRef object) +{ + //LogDebug("enter"); +} + +void JSAttributesOfInterestArray::finalize(JSObjectRef object) +{ + //LogDebug("enter"); + JSAttributesOfInterestArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSAttributesOfInterestArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + //LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSAttributesOfInterestArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + AttributesOfInterestArrayPtr typeArray = priv->getObject(); + if (index < typeArray->size()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSAttributesOfInterestArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSAttributesOfInterestArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + AttributesOfInterestArrayPtr typeArray = priv->getObject(); + if (index < typeArray->size()) { + std::string result = typeArray->at(index); + if (!result.empty()) { + return converter->toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSAttributesOfInterestArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + //LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + std::string str; + if (!JSValueIsUndefined(context, value)) { + str = converter->toString(value); + } + JSAttributesOfInterestArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + AttributesOfInterestArrayPtr typeArray = priv->getObject(); + if (!typeArray) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (typeArray->size() <= index) { + typeArray->resize(index + 1); + } + (*typeArray)[index] = str; + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + } + return false; +} + +JSValueRef JSAttributesOfInterestArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + AttributesOfInterestArrayPtr typeArray = + AttributesOfInterestArrayPtr(new AttributesOfInterestArray()); + JSAttributesOfInterestArrayPriv *newPrivateObject = + new JSAttributesOfInterestArrayPriv(context, typeArray); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current typeArray + JSAttributesOfInterestArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + AttributesOfInterestArrayPtr currentStrings = priv->getObject(); + for (size_t i = 0; i < currentStrings->size(); ++i) { + typeArray->push_back(currentStrings->at(i)); + } + + //copy submitted arrays + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + typeArray->push_back(converter->toString(att)); + } + } + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSAttributesOfInterestArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSAttributesOfInterestArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + AttributesOfInterestArrayPtr currentStrings = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentStrings->size(); ++i) { + if (i != 0) { + result += separator; + } + result += currentStrings->at(i); + } + return converter->toJSValueRef(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSAttributesOfInterestArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSAttributesOfInterestArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + AttributesOfInterestArrayPtr currentStrings = priv->getObject(); + if (currentStrings->size() > 0) { + std::string result = currentStrings->at( + currentStrings->size() - 1); + currentStrings->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSAttributesOfInterestArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSAttributesOfInterestArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + AttributesOfInterestArrayPtr currentStrings = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentStrings->push_back(converter->toString(arguments[i])); + } + return converter->toJSValueRef(currentStrings->size()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSAttributesOfInterestArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSAttributesOfInterestArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + AttributesOfInterestArrayPtr currentStrings = priv->getObject(); + std::reverse(currentStrings->begin(), currentStrings->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSAttributesOfInterestArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSAttributesOfInterestArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + AttributesOfInterestArrayPtr currentStrings = priv->getObject(); + if (currentStrings->size() > 0) { + std::string result = currentStrings->at(0); + currentStrings->erase(currentStrings->begin()); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSAttributesOfInterestArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + AttributesOfInterestArrayPtr typeArray = AttributesOfInterestArrayPtr(new StringArray()); + JSAttributesOfInterestArrayPriv *newPrivateObject = new JSAttributesOfInterestArrayPriv( + context, + typeArray); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current typeArray + JSAttributesOfInterestArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + AttributesOfInterestArrayPtr currentStrings = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentStrings->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentStrings->size()) { + last = currentStrings->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + typeArray->push_back(currentStrings->at(i)); + } + + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSAttributesOfInterestArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSAttributesOfInterestArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + AttributesOfInterestArrayPtr currentStrings = priv->getObject(); + std::sort(currentStrings->begin(), currentStrings->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSAttributesOfInterestArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSAttributesOfInterestArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSAttributesOfInterestArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSAttributesOfInterestArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSAttributesOfInterestArray.h b/src/standards/Tizen/Contact/JSAttributesOfInterestArray.h new file mode 100755 index 0000000..257f188 --- /dev/null +++ b/src/standards/Tizen/Contact/JSAttributesOfInterestArray.h @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSAttributesOfInterestArray.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_ATTRIBUTES_OF_INTEREST_ARRAY_H_ +#define _TIZEN_CONTACT_JS_ATTRIBUTES_OF_INTEREST_ARRAY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSAttributesOfInterestArrayPriv; + +class JSAttributesOfInterestArray +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const TizenApis::Api::Contact::AttributesOfInterestArrayPtr &Strings); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::AttributesOfInterestArrayPtr getAttributesOfInterestArray(JSContextRef context, JSValueRef value); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_ATTRIBUTES_OF_INTEREST_ARRAY_H_ diff --git a/src/standards/Tizen/Contact/JSContact.cpp b/src/standards/Tizen/Contact/JSContact.cpp new file mode 100755 index 0000000..84bceff --- /dev/null +++ b/src/standards/Tizen/Contact/JSContact.cpp @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContact.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSContact class + */ + +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactProperties.h" +#include "JSContact.h" + +#define FILTER_CLASS_NAME "Contact" + +#define CONTACT_ATTR_ID "id" +#define CONTACT_ATTR_READ_ONLY "readOnly" +#define CONTACT_ATTR_LAST_UPDATED "lastUpdated" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Api::Contact; + +using TizenApis::Api::Contact::Contact; + +JSClassRef JSContact::m_classRef = NULL; + +JSClassDefinition JSContact::m_classInfo = +{ + 0, + kJSClassAttributeNone, + FILTER_CLASS_NAME, + JSContactProperties::getClassRef(), + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticValue JSContact::m_property[] = { + { CONTACT_ATTR_ID, getId, NULL, kJSPropertyAttributeReadOnly }, + { CONTACT_ATTR_READ_ONLY, getReadOnly, NULL, kJSPropertyAttributeReadOnly }, + { CONTACT_ATTR_LAST_UPDATED, getLastUpdated, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContact::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSContact::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSContact::createJSObject(JSContextRef context + // FIXME + ) +{ + ContactPtr privateData = ContactPtr(new Contact()); + JSContactPriv *priv = new JSContactPriv(context, privateData); + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast(priv)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +bool JSContact::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactPtr JSContact::getContact(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSContact::Initialize(JSContextRef context, JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSContact::Finalize(JSObjectRef object) +{ + //delete (JSObjectGetPrivate(object)); +} + +ContactPtr JSContact::getPrivData(JSObjectRef object) +{ + LogDebug("entered"); + JSContactPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + ContactPtr result = priv->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + return result; +} + +JSValueRef JSContact::getId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPtr contact = getPrivData(object); + return converter->toJSValueRef(contact->getId()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContact::getReadOnly(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPtr contact = getPrivData(object); + return converter->toJSValueRef(contact->getReadOnly()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSContact::getLastUpdated(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPtr contact = getPrivData(object); + return converter->toJSValueRef(contact->getLastUpdated()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContact.h b/src/standards/Tizen/Contact/JSContact.h new file mode 100755 index 0000000..07cd388 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContact.h @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContact.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSContact class + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_H_ +#define _TIZEN_CONTACT_JS_CONTACT_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject JSContactPriv; + +class JSContact { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context + // FIXME fix this value + ); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactPtr getContact(JSContextRef context, JSValueRef value); + +private: + /** + * The callback invoked when an object is first created. + */ + static void Initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void Finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static TizenApis::Api::Contact::ContactPtr getPrivData(JSObjectRef object); + + static JSValueRef getId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getReadOnly(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getLastUpdated(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_H_ diff --git a/src/standards/Tizen/Contact/JSContactAccount.cpp b/src/standards/Tizen/Contact/JSContactAccount.cpp new file mode 100755 index 0000000..50d7ab0 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactAccount.cpp @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactAccount.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSContactAccount class + */ + +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactAccount.h" + +#define ORGANIZATION_CLASS_NAME "ContactAccount" + +#define CONTACT_ATTR_ACCOUNT_ID "accountId" +#define CONTACT_ATTR_CONTACT_URI "contactUri" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassRef JSContactAccount::m_classRef = NULL; + +JSClassDefinition JSContactAccount::m_classInfo = +{ + 0, + kJSClassAttributeNone, + ORGANIZATION_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticValue JSContactAccount::m_property[] = { + { CONTACT_ATTR_ACCOUNT_ID, getAccountId, setAccountId, kJSPropertyAttributeNone }, + { CONTACT_ATTR_CONTACT_URI, getContactURI, setContactURI, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactAccount::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSContactAccount::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSContactAccount::createJSObject(JSContextRef context, + const std::string& accountId, + const std::string& contactURI) +{ + ContactAccountPtr privateData = ContactAccountPtr(new ContactAccount()); + privateData->setAccountId(accountId); + privateData->setContactURI(contactURI); + JSContactAccountPriv *priv = new JSContactAccountPriv(context, privateData); + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast(priv)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +bool JSContactAccount::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactAccountPtr JSContactAccount::getContactAccount(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactAccountPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSContactAccount::Initialize(JSContextRef context, JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSContactAccount::Finalize(JSObjectRef object) +{ + //delete (JSObjectGetPrivate(object)); +} + +ContactAccountPtr JSContactAccount::getPrivData(JSObjectRef object) +{ + //LogDebug("entered"); + JSContactAccountPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + ContactAccountPtr result = priv->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + return result; +} + +JSValueRef JSContactAccount::getAccountId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyAccountId, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactAccountPtr organization = getPrivData(object); + return converter->toJSValueRef(organization->getAccountId()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAccount::setAccountId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyAccountId, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactAccountPtr organization = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + organization->setAccountId(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactAccount::getContactURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactAccountPtr organization = getPrivData(object); + return converter->toJSValueRef(organization->getContactURI()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAccount::setContactURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactAccountPtr organization = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + organization->setContactURI(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactAccount.h b/src/standards/Tizen/Contact/JSContactAccount.h new file mode 100755 index 0000000..2d89785 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactAccount.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactAccount.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSContactAccount class + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_ACCOUNT_H_ +#define _TIZEN_CONTACT_JS_CONTACT_ACCOUNT_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject JSContactAccountPriv; + +class JSContactAccount { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context, + const std::string& accountId, + const std::string& contactURI); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactAccountPtr getContactAccount(JSContextRef context, JSValueRef value); + +private: + /** + * The callback invoked when an object is first created. + */ + static void Initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void Finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static TizenApis::Api::Contact::ContactAccountPtr getPrivData(JSObjectRef object); + + static JSValueRef getAccountId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setAccountId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getContactURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setContactURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_ACCOUNT_H_ diff --git a/src/standards/Tizen/Contact/JSContactAddress.cpp b/src/standards/Tizen/Contact/JSContactAddress.cpp new file mode 100755 index 0000000..b5bff3d --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactAddress.cpp @@ -0,0 +1,476 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactAddress.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSContactAddress class + */ + +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactAddress.h" +#include "JSContactAddressTypeArray.h" + +#define CONTACT_CLASS_NAME "ContactAddress" + +#define CONTACT_ATTR_COUNTRY "country" +#define CONTACT_ATTR_REGION "region" +#define CONTACT_ATTR_CITY "city" +#define CONTACT_ATTR_STREET_ADDRESS "streetAddress" +#define CONTACT_ATTR_ADDITIONAL_INFORMATION "additionalInformation" +#define CONTACT_ATTR_POSTAL_CODE "postalCode" +#define CONTACT_ATTR_TYPES "types" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassRef JSContactAddress::m_classRef = NULL; + +JSClassDefinition JSContactAddress::m_classInfo = +{ + 0, + kJSClassAttributeNone, + CONTACT_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticValue JSContactAddress::m_property[] = { + { CONTACT_ATTR_COUNTRY, getCountry, setCountry, kJSPropertyAttributeNone }, + { CONTACT_ATTR_REGION, getRegion, setRegion, kJSPropertyAttributeNone }, + { CONTACT_ATTR_CITY, getCity, setCity, kJSPropertyAttributeNone }, + { CONTACT_ATTR_STREET_ADDRESS, getStreetAddress, setStreetAddress, kJSPropertyAttributeNone }, + { CONTACT_ATTR_ADDITIONAL_INFORMATION, getAdditionalInformation, setAdditionalInformation, kJSPropertyAttributeNone }, + { CONTACT_ATTR_POSTAL_CODE, getPostalCode, setPostalCode, kJSPropertyAttributeNone }, + { CONTACT_ATTR_TYPES, getTypes, setTypes, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactAddress::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSContactAddress::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSContactAddress::createJSObject(JSContextRef context, + const std::string country, + const std::string region, + const std::string county, + const std::string city, + const std::string streetAddress, + const std::string additionalInformation, + const std::string postalCode, + const ContactAddressTypeArrayPtr types) +{ + ContactAddressPtr privateData = ContactAddressPtr(new ContactAddress()); + + privateData->setCountry(country); + privateData->setRegion(region); + privateData->setCity(city); + privateData->setStreetAddress(streetAddress); + privateData->setAdditionalInformation(additionalInformation); + privateData->setPostalCode(postalCode); + privateData->setTypes(types); + + JSContactAddressPriv *priv = new JSContactAddressPriv(context, privateData); + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast(priv)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +bool JSContactAddress::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactAddressPtr JSContactAddress::getContactAddress(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactAddressPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSContactAddress::Initialize(JSContextRef context, JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSContactAddress::Finalize(JSObjectRef object) +{ + //delete (JSObjectGetPrivate(object)); +} + +ContactAddressPtr JSContactAddress::getPrivData(JSObjectRef object) +{ + //LogDebug("entered"); + JSContactAddressPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + ContactAddressPtr result = priv->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + return result; +} + +JSValueRef JSContactAddress::getCountry(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactAddressPtr contactAddress = getPrivData(object); + return converter->toJSValueRef(contactAddress->getCountry()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAddress::setCountry(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactAddressPtr contactAddress = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactAddress->setCountry(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + + +JSValueRef JSContactAddress::getRegion(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactAddressPtr contactAddress = getPrivData(object); + return converter->toJSValueRef(contactAddress->getRegion()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAddress::setRegion(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactAddressPtr contactAddress = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactAddress->setRegion(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactAddress::getCity(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactAddressPtr contactAddress = getPrivData(object); + return converter->toJSValueRef(contactAddress->getCity()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAddress::setCity(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactAddressPtr contactAddress = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactAddress->setCity(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + + +JSValueRef JSContactAddress::getStreetAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactAddressPtr contactAddress = getPrivData(object); + return converter->toJSValueRef(contactAddress->getStreetAddress()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAddress::setStreetAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactAddressPtr contactAddress = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactAddress->setStreetAddress(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + + +JSValueRef JSContactAddress::getAdditionalInformation(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactAddressPtr contactAddress = getPrivData(object); + return converter->toJSValueRef(contactAddress->getAdditionalInformation()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAddress::setAdditionalInformation(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactAddressPtr contactAddress = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactAddress->setAdditionalInformation(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + + +JSValueRef JSContactAddress::getPostalCode(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactAddressPtr contactAddress = getPrivData(object); + return converter->toJSValueRef(contactAddress->getPostalCode()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAddress::setPostalCode(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactAddressPtr contactAddress = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactAddress->setPostalCode(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + + +JSValueRef JSContactAddress::getTypes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactAddressPtr contactAddress = getPrivData(object); + return JSContactAddressTypeArray::createArray(context, contactAddress->getTypes()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAddress::setTypes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactAddressPtr contactAddress = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + + + if(JSContactAddressTypeArray::isObjectOfClass(context, value)) + contactAddress->setTypes(converter->toContactAddressTypeArray(value)); // TODO to implement this function on converter + else + contactAddress->setTypes(JSContactAddressTypeArray::getContactAddressTypeArray(context, value)); + + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactAddress.h b/src/standards/Tizen/Contact/JSContactAddress.h new file mode 100755 index 0000000..9788954 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactAddress.h @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactAddress.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSContactAddress class + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_ADDRESS_H_ +#define _TIZEN_CONTACT_JS_CONTACT_ADDRESS_H_ + +#include +#include +#include +#include +#include +#include "JSContactEmailAddressTypeArray.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject JSContactAddressPriv; + +class JSContactAddress { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context, + const std::string country = "", + const std::string region = "", + const std::string county = "", + const std::string city = "", + const std::string streetAddress = "", + const std::string additionalInformation = "", + const std::string postalCode = "", + const TizenApis::Api::Contact::ContactAddressTypeArrayPtr types = TizenApis::Api::Contact::ContactAddressTypeArrayPtr(new TizenApis::Api::Contact::ContactAddressTypeArray())); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactAddressPtr getContactAddress(JSContextRef context, JSValueRef value); + +private: + /** + * The callback invoked when an object is first created. + */ + static void Initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void Finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static TizenApis::Api::Contact::ContactAddressPtr getPrivData(JSObjectRef object); + + static JSValueRef getCountry(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setCountry(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getRegion(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setRegion(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getCity(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setCity(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getStreetAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setStreetAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getAdditionalInformation(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setAdditionalInformation(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getPostalCode(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setPostalCode(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getTypes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setTypes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_ADDRESS_H_ diff --git a/src/standards/Tizen/Contact/JSContactAddressArray.cpp b/src/standards/Tizen/Contact/JSContactAddressArray.cpp new file mode 100755 index 0000000..f3e3733 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactAddressArray.cpp @@ -0,0 +1,589 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactAddressArray.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactAddressArray.h" + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassDefinition JSContactAddressArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSContactAddressArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactAddressArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSContactAddressArray::m_jsClassRef = JSClassCreate( + JSContactAddressArray::getClassInfo()); + +JSValueRef JSContactAddressArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + JSContactAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactAddressArrayPtr contactAddresses = priv->getObject(); + if (contactAddresses) { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + return converter->toJSValueRef(contactAddresses->size()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSContactAddressArray::createArray(JSContextRef context, + const ContactAddressArrayPtr &contactAddresses) +{ + JSContactAddressArrayPriv *priv = new JSContactAddressArrayPriv(context, contactAddresses); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSContactAddressArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSContactAddressArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +bool JSContactAddressArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactAddressArrayPtr JSContactAddressArray::getContactAddressArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactAddressArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSContactAddressArray::initialize(JSContextRef context, + JSObjectRef object) +{ + //LogDebug("enter"); +} + +void JSContactAddressArray::finalize(JSObjectRef object) +{ + //LogDebug("enter"); + JSContactAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSContactAddressArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactAddressArrayPtr contactAddresses = priv->getObject(); + if (index < contactAddresses->size()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSContactAddressArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactAddressArrayPtr contactAddresses = priv->getObject(); + if (index < contactAddresses->size()) { + ContactAddressPtr result = contactAddresses->at(index); + if (result) { + return converter->toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAddressArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + ContactAddressPtr contactAddress; + if (!JSValueIsUndefined(context, value)) { + contactAddress = converter->toContactAddress(value); + } + JSContactAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactAddressArrayPtr contactAddresses = priv->getObject(); + if (!contactAddresses) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (contactAddresses->size() <= index) { + contactAddresses->resize(index + 1); + } + (*contactAddresses)[index] = contactAddress; + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + } + return false; +} + +JSValueRef JSContactAddressArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + ContactAddressArrayPtr contactAddresses = ContactAddressArrayPtr(new ContactAddressArray()); + JSContactAddressArrayPriv *newPrivateObject = new JSContactAddressArrayPriv(context, contactAddresses); + JSValueRef result = JSObjectMake(context, getClassRef(), newPrivateObject); + + //copy current contactAddresses + JSContactAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressArrayPtr currentContactAddresses = priv->getObject(); + for (size_t i = 0; i < currentContactAddresses->size(); ++i) { + contactAddresses->push_back(currentContactAddresses->at(i)); + } + + //copy submitted arrays + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + contactAddresses->push_back(converter->toContactAddress(att)); + } + } + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactAddressArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressArrayPtr currentContactAddresses = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentContactAddresses->size(); ++i) { + if (i != 0) { + result += separator; + } + //FIXME : to be changed to support join + //result += currentContactAddresses->at(i); + } + return converter->toJSValueRef(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactAddressArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressArrayPtr currentContactAddresses = priv->getObject(); + if (currentContactAddresses->size() > 0) { + ContactAddressPtr result = currentContactAddresses->at( + currentContactAddresses->size() - 1); + currentContactAddresses->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAddressArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressArrayPtr currentContactAddresses = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentContactAddresses->push_back(converter->toContactAddress(arguments[i])); + } + return converter->toJSValueRef(currentContactAddresses->size()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactAddressArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressArrayPtr currentContactAddresses = priv->getObject(); + std::reverse(currentContactAddresses->begin(), currentContactAddresses->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAddressArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressArrayPtr currentContactAddresses = priv->getObject(); + if (currentContactAddresses->size() > 0) { + ContactAddressPtr result = currentContactAddresses->at(0); + currentContactAddresses->erase(currentContactAddresses->begin()); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAddressArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactAddressArrayPtr contactAddresses = ContactAddressArrayPtr(new ContactAddressArray()); + JSContactAddressArrayPriv *newPrivateObject = new JSContactAddressArrayPriv( + context, + contactAddresses); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current contactAddresses + JSContactAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressArrayPtr currentContactAddresses = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentContactAddresses->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentContactAddresses->size()) { + last = currentContactAddresses->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + contactAddresses->push_back(currentContactAddresses->at(i)); + } + + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactAddressArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressArrayPtr currentContactAddresses = priv->getObject(); + std::sort(currentContactAddresses->begin(), currentContactAddresses->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAddressArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAddressArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSContactAddressArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAddressArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactAddressArray.h b/src/standards/Tizen/Contact/JSContactAddressArray.h new file mode 100755 index 0000000..8a9baaf --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactAddressArray.h @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactAddressArray.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_ADDRESS_ARRAY_H_ +#define _TIZEN_CONTACT_JS_CONTACT_ADDRESS_ARRAY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSContactAddressArrayPriv; + +class JSContactAddressArray +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const TizenApis::Api::Contact::ContactAddressArrayPtr &contactAddresses); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactAddressArrayPtr getContactAddressArray(JSContextRef context, JSValueRef value); + + private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif /* _TIZEN_CONTACT_JS_CONTACT_ADDRESS_ARRAY_H_ */ diff --git a/src/standards/Tizen/Contact/JSContactAddressTypeArray.cpp b/src/standards/Tizen/Contact/JSContactAddressTypeArray.cpp new file mode 100755 index 0000000..456d770 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactAddressTypeArray.cpp @@ -0,0 +1,591 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactAddressTypeArray.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactAddressTypeArray.h" + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassDefinition JSContactAddressTypeArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSContactAddressTypeArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactAddressTypeArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSContactAddressTypeArray::m_jsClassRef = JSClassCreate( + JSContactAddressTypeArray::getClassInfo()); + +JSValueRef JSContactAddressTypeArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + JSContactAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactAddressTypeArrayPtr typeArray = priv->getObject(); + if (typeArray) { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + return converter->toJSValueRef(typeArray->size()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSContactAddressTypeArray::createArray(JSContextRef context, + const ContactAddressTypeArrayPtr &typeArray) +{ + JSContactAddressTypeArrayPriv *priv = new JSContactAddressTypeArrayPriv(context, typeArray); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSContactAddressTypeArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSContactAddressTypeArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +bool JSContactAddressTypeArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactAddressTypeArrayPtr JSContactAddressTypeArray::getContactAddressTypeArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactAddressTypeArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSContactAddressTypeArray::initialize(JSContextRef context, + JSObjectRef object) +{ + //LogDebug("enter"); +} + +void JSContactAddressTypeArray::finalize(JSObjectRef object) +{ + //LogDebug("enter"); + JSContactAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSContactAddressTypeArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + //LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactAddressTypeArrayPtr typeArray = priv->getObject(); + if (index < typeArray->size()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSContactAddressTypeArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactAddressTypeArrayPtr typeArray = priv->getObject(); + if (index < typeArray->size()) { + std::string result = converter->toContactAddressTypeStr(typeArray->at(index)); + if (!result.empty()) { + return converter->toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAddressTypeArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + std::string str; + if (!JSValueIsUndefined(context, value)) { + str = converter->toString(value); + } + JSContactAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactAddressTypeArrayPtr typeArray = priv->getObject(); + if (!typeArray) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (typeArray->size() <= index) { + typeArray->resize(index + 1); + } + (*typeArray)[index] = converter->toContactAddressType(str); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + } + return false; +} + +JSValueRef JSContactAddressTypeArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + ContactAddressTypeArrayPtr typeArray = ContactAddressTypeArrayPtr(new ContactAddressTypeArray()); + JSContactAddressTypeArrayPriv *newPrivateObject = new JSContactAddressTypeArrayPriv( + context, + typeArray); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current typeArray + JSContactAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressTypeArrayPtr currentTypes = priv->getObject(); + for (size_t i = 0; i < currentTypes->size(); ++i) { + typeArray->push_back(currentTypes->at(i)); + } + + //copy submitted arrays + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + // process array of types + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + typeArray->push_back(converter->toContactAddressType(att)); + } + } + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactAddressTypeArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSContactAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressTypeArrayPtr currentTypes = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentTypes->size(); ++i) { + if (i != 0) { + result += separator; + } + result += currentTypes->at(i); + } + return converter->toJSValueRef(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactAddressTypeArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressTypeArrayPtr currentTypes = priv->getObject(); + if (currentTypes->size() > 0) { + std::string result = converter->toContactAddressTypeStr(currentTypes->at(currentTypes->size()-1)); + currentTypes->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAddressTypeArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressTypeArrayPtr currentTypes = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentTypes->push_back(converter->toContactAddressType(arguments[i])); + } + return converter->toJSValueRef(currentTypes->size()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactAddressTypeArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSContactAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressTypeArrayPtr currentTypes = priv->getObject(); + std::reverse(currentTypes->begin(), currentTypes->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAddressTypeArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressTypeArrayPtr currentTypes = priv->getObject(); + if (currentTypes->size() > 0) { + std::string result = converter->toContactAddressTypeStr(currentTypes->at(0)); + currentTypes->erase(currentTypes->begin()); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAddressTypeArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + ContactAddressTypeArrayPtr typeArray = ContactAddressTypeArrayPtr(new ContactAddressTypeArray()); + JSContactAddressTypeArrayPriv *newPrivateObject = new JSContactAddressTypeArrayPriv( + context, + typeArray); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current typeArray + JSContactAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressTypeArrayPtr currentTypes = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentTypes->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentTypes->size()) { + last = currentTypes->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + typeArray->push_back(currentTypes->at(i)); + } + + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactAddressTypeArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSContactAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAddressTypeArrayPtr currentTypes = priv->getObject(); + std::sort(currentTypes->begin(), currentTypes->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAddressTypeArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAddressTypeArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSContactAddressTypeArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAddressTypeArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactAddressTypeArray.h b/src/standards/Tizen/Contact/JSContactAddressTypeArray.h new file mode 100755 index 0000000..71ebf25 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactAddressTypeArray.h @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactAddressTypeArray.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_ADDRESS_TYPE_ARRAY_H_ +#define _TIZEN_CONTACT_JS_CONTACT_ADDRESS_TYPE_ARRAY_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSContactAddressTypeArrayPriv; + +class JSContactAddressTypeArray +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const TizenApis::Api::Contact::ContactAddressTypeArrayPtr &Strings); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactAddressTypeArrayPtr getContactAddressTypeArray(JSContextRef context, JSValueRef value); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_ADDRESS_TYPE_ARRAY_H_ diff --git a/src/standards/Tizen/Contact/JSContactAnniversary.cpp b/src/standards/Tizen/Contact/JSContactAnniversary.cpp new file mode 100755 index 0000000..dff4fea --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactAnniversary.cpp @@ -0,0 +1,230 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactAnniversary.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSContactAnniversary class + */ + +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactAnniversary.h" + +#define FILTER_CLASS_NAME "Anniversary" +#define CONTACT_ATTR_DATE "date" +#define CONTACT_ATTR_LABEL "label" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassRef JSContactAnniversary::m_classRef = NULL; + +JSClassDefinition JSContactAnniversary::m_classInfo = +{ + 0, + kJSClassAttributeNone, + FILTER_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticValue JSContactAnniversary::m_property[] = { + { CONTACT_ATTR_DATE, getDate, setDate, kJSPropertyAttributeNone }, + //{ CONTACT_ATTR_LABEL, getLabel, setLabel, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactAnniversary::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSContactAnniversary::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSContactAnniversary::createJSObject(JSContextRef context, + const std::tm &date, + const std::string& label) +{ + ContactAnniversaryPtr privateData = ContactAnniversaryPtr(new ContactAnniversary()); + privateData->setDate(date); + //privateData->setLabel(label); + JSContactAnniversaryPriv *priv = new JSContactAnniversaryPriv(context, privateData); + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast(priv)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +bool JSContactAnniversary::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactAnniversaryPtr JSContactAnniversary::getContactAnniversary(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactAnniversaryPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSContactAnniversary::Initialize(JSContextRef context, JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSContactAnniversary::Finalize(JSObjectRef object) +{ + //delete (JSObjectGetPrivate(object)); +} + +ContactAnniversaryPtr JSContactAnniversary::getPrivData(JSObjectRef object) +{ + //LogDebug("entered"); + JSContactAnniversaryPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + ContactAnniversaryPtr result = priv->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + return result; +} + +JSValueRef JSContactAnniversary::getDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactAnniversaryPtr anniversary = getPrivData(object); + return converter->toJSValueRef(anniversary->getDate()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAnniversary::setDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactAnniversaryPtr anniversary = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + anniversary->setDate(converter->toDateTm(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactAnniversary::getLabel(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactAnniversaryPtr anniversary = getPrivData(object); + return converter->toJSValueRef(anniversary->getLabel()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAnniversary::setLabel(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactAnniversaryPtr anniversary = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + anniversary->setLabel(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactAnniversary.h b/src/standards/Tizen/Contact/JSContactAnniversary.h new file mode 100755 index 0000000..279c145 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactAnniversary.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactAnniversary.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSContactAnniversary class + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_ANNIVERSARY_H_ +#define _TIZEN_CONTACT_JS_CONTACT_ANNIVERSARY_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject JSContactAnniversaryPriv; + +class JSContactAnniversary { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context, + const std::tm &date, + const std::string& label = ""); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactAnniversaryPtr getContactAnniversary(JSContextRef context, JSValueRef value); + +private: + /** + * The callback invoked when an object is first created. + */ + static void Initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void Finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static TizenApis::Api::Contact::ContactAnniversaryPtr getPrivData(JSObjectRef object); + + static JSValueRef getDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getLabel(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setLabel(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_ANNIVERSARY_H_ diff --git a/src/standards/Tizen/Contact/JSContactAnniversaryArray.cpp b/src/standards/Tizen/Contact/JSContactAnniversaryArray.cpp new file mode 100755 index 0000000..a7dc914 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactAnniversaryArray.cpp @@ -0,0 +1,589 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactAnniversaryArray.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactAnniversaryArray.h" + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassDefinition JSContactAnniversaryArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSContactAnniversaryArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactAnniversaryArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSContactAnniversaryArray::m_jsClassRef = JSClassCreate( + JSContactAnniversaryArray::getClassInfo()); + +JSValueRef JSContactAnniversaryArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + ////LogDebug("enter"); + Try + { + JSContactAnniversaryArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactAnniversaryArrayPtr anniversaries = priv->getObject(); + if (anniversaries) { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + return converter->toJSValueRef(anniversaries->size()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSContactAnniversaryArray::createArray(JSContextRef context, + const ContactAnniversaryArrayPtr &anniversaries) +{ + JSContactAnniversaryArrayPriv *priv = new JSContactAnniversaryArrayPriv(context, anniversaries); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSContactAnniversaryArray::getClassInfo() +{ + return &(m_classInfo); +} + +bool JSContactAnniversaryArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactAnniversaryArrayPtr JSContactAnniversaryArray::getContactAnniversaryArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactAnniversaryArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +JSClassRef JSContactAnniversaryArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +void JSContactAnniversaryArray::initialize(JSContextRef context, + JSObjectRef object) +{ + //LogDebug("enter"); +} + +void JSContactAnniversaryArray::finalize(JSObjectRef object) +{ + //LogDebug("enter"); + JSContactAnniversaryArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSContactAnniversaryArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactAnniversaryArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactAnniversaryArrayPtr anniversaries = priv->getObject(); + if (index < anniversaries->size()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSContactAnniversaryArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactAnniversaryArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactAnniversaryArrayPtr anniversaries = priv->getObject(); + if (index < anniversaries->size()) { + ContactAnniversaryPtr result = anniversaries->at(index); + if (result) { + return converter->toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactAnniversaryArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + ContactAnniversaryPtr anniversary; + if (!JSValueIsUndefined(context, value)) { + anniversary = converter->toContactAnniversary(value); + } + JSContactAnniversaryArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactAnniversaryArrayPtr anniversaries = priv->getObject(); + if (!anniversaries) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (anniversaries->size() <= index) { + anniversaries->resize(index + 1); + } + (*anniversaries)[index] = anniversary; + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + } + return false; +} + +JSValueRef JSContactAnniversaryArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + ContactAnniversaryArrayPtr anniversaries = ContactAnniversaryArrayPtr(new ContactAnniversaryArray()); + JSContactAnniversaryArrayPriv *newPrivateObject = new JSContactAnniversaryArrayPriv(context, anniversaries); + JSValueRef result = JSObjectMake(context, getClassRef(), newPrivateObject); + + //copy current anniversaries + JSContactAnniversaryArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAnniversaryArrayPtr currentAnniversaries = priv->getObject(); + for (size_t i = 0; i < currentAnniversaries->size(); ++i) { + anniversaries->push_back(currentAnniversaries->at(i)); + } + + //copy submitted arrays + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + anniversaries->push_back(converter->toContactAnniversary(att)); + } + } + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactAnniversaryArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAnniversaryArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAnniversaryArrayPtr currentAnniversaries = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentAnniversaries->size(); ++i) { + if (i != 0) { + result += separator; + } + //FIXME : to be changed to support join + //result += currentAnniversaries->at(i); + } + return converter->toJSValueRef(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactAnniversaryArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAnniversaryArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAnniversaryArrayPtr currentAnniversaries = priv->getObject(); + if (currentAnniversaries->size() > 0) { + ContactAnniversaryPtr result = currentAnniversaries->at( + currentAnniversaries->size() - 1); + currentAnniversaries->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAnniversaryArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAnniversaryArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAnniversaryArrayPtr currentAnniversaries = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentAnniversaries->push_back(converter->toContactAnniversary(arguments[i])); + } + return converter->toJSValueRef(currentAnniversaries->size()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactAnniversaryArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAnniversaryArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAnniversaryArrayPtr currentAnniversaries = priv->getObject(); + std::reverse(currentAnniversaries->begin(), currentAnniversaries->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAnniversaryArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAnniversaryArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAnniversaryArrayPtr currentAnniversaries = priv->getObject(); + if (currentAnniversaries->size() > 0) { + ContactAnniversaryPtr result = currentAnniversaries->at(0); + currentAnniversaries->erase(currentAnniversaries->begin()); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAnniversaryArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactAnniversaryArrayPtr anniversaries = ContactAnniversaryArrayPtr(new ContactAnniversaryArray()); + JSContactAnniversaryArrayPriv *newPrivateObject = new JSContactAnniversaryArrayPriv( + context, + anniversaries); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current anniversaries + JSContactAnniversaryArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAnniversaryArrayPtr currentAnniversaries = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentAnniversaries->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentAnniversaries->size()) { + last = currentAnniversaries->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + anniversaries->push_back(currentAnniversaries->at(i)); + } + + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactAnniversaryArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactAnniversaryArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactAnniversaryArrayPtr currentAnniversaries = priv->getObject(); + std::sort(currentAnniversaries->begin(), currentAnniversaries->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAnniversaryArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAnniversaryArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSContactAnniversaryArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactAnniversaryArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactAnniversaryArray.h b/src/standards/Tizen/Contact/JSContactAnniversaryArray.h new file mode 100755 index 0000000..bc8c636 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactAnniversaryArray.h @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactAnniversaryArray.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_ANNIVERSARY_ARRAY_H_ +#define _TIZEN_CONTACT_JS_CONTACT_ANNIVERSARY_ARRAY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSContactAnniversaryArrayPriv; + +class JSContactAnniversaryArray +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const TizenApis::Api::Contact::ContactAnniversaryArrayPtr &anniversaries); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactAnniversaryArrayPtr getContactAnniversaryArray(JSContextRef context, JSValueRef value); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_ANNIVERSARY_ARRAY_H_ diff --git a/src/standards/Tizen/Contact/JSContactArray.cpp b/src/standards/Tizen/Contact/JSContactArray.cpp new file mode 100755 index 0000000..69c88ed --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactArray.cpp @@ -0,0 +1,589 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactArray.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactArray.h" + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassDefinition JSContactArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSContactArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSContactArray::m_jsClassRef = JSClassCreate( + JSContactArray::getClassInfo()); + +JSValueRef JSContactArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + JSContactArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactArrayPtr contacts = priv->getObject(); + if (contacts) { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + return converter->toJSValueRef(contacts->size()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSContactArray::createArray(JSContextRef context, + const ContactArrayPtr &contacts) +{ + JSContactArrayPriv *priv = new JSContactArrayPriv(context, contacts); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSContactArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSContactArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +bool JSContactArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactArrayPtr JSContactArray::getContactArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSContactArray::initialize(JSContextRef context, + JSObjectRef object) +{ + //LogDebug("enter"); +} + +void JSContactArray::finalize(JSObjectRef object) +{ + //LogDebug("enter"); + JSContactArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSContactArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactArrayPtr contacts = priv->getObject(); + if (index < contacts->size()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSContactArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactArrayPtr contacts = priv->getObject(); + if (index < contacts->size()) { + ContactPtr result = contacts->at(index); + if (result) { + return converter->toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + ContactPtr contact; + if (!JSValueIsUndefined(context, value)) { + contact = converter->toContact(value); + } + JSContactArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactArrayPtr contacts = priv->getObject(); + if (!contacts) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (contacts->size() <= index) { + contacts->resize(index + 1); + } + (*contacts)[index] = contact; + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + } + return false; +} + +JSValueRef JSContactArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + ContactArrayPtr contacts = ContactArrayPtr(new ContactArray()); + JSContactArrayPriv *newPrivateObject = new JSContactArrayPriv(context, contacts); + JSValueRef result = JSObjectMake(context, getClassRef(), newPrivateObject); + + //copy current contacts + JSContactArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactArrayPtr currentContacts = priv->getObject(); + for (size_t i = 0; i < currentContacts->size(); ++i) { + contacts->push_back(currentContacts->at(i)); + } + + //copy submitted arrays + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + contacts->push_back(converter->toContact(att)); + } + } + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactArrayPtr currentContacts = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentContacts->size(); ++i) { + if (i != 0) { + result += separator; + } + //FIXME : to be changed to support join + //result += currentContacts->at(i); + } + return converter->toJSValueRef(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactArrayPtr currentContacts = priv->getObject(); + if (currentContacts->size() > 0) { + ContactPtr result = currentContacts->at( + currentContacts->size() - 1); + currentContacts->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactArrayPtr currentContacts = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentContacts->push_back(converter->toContact(arguments[i])); + } + return converter->toJSValueRef(currentContacts->size()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactArrayPtr currentContacts = priv->getObject(); + std::reverse(currentContacts->begin(), currentContacts->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactArrayPtr currentContacts = priv->getObject(); + if (currentContacts->size() > 0) { + ContactPtr result = currentContacts->at(0); + currentContacts->erase(currentContacts->begin()); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactArrayPtr contacts = ContactArrayPtr(new ContactArray()); + JSContactArrayPriv *newPrivateObject = new JSContactArrayPriv( + context, + contacts); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current contacts + JSContactArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactArrayPtr currentContacts = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentContacts->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentContacts->size()) { + last = currentContacts->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + contacts->push_back(currentContacts->at(i)); + } + + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactArrayPtr currentContacts = priv->getObject(); + std::sort(currentContacts->begin(), currentContacts->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSContactArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactArray.h b/src/standards/Tizen/Contact/JSContactArray.h new file mode 100755 index 0000000..b6323d2 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactArray.h @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactArray.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_ARRAY_H_ +#define _TIZEN_CONTACT_JS_CONTACT_ARRAY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSContactArrayPriv; + +class JSContactArray +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const TizenApis::Api::Contact::ContactArrayPtr &contactAddresses); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactArrayPtr getContactArray(JSContextRef context, JSValueRef value); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_ARRAY_H_ diff --git a/src/standards/Tizen/Contact/JSContactEmailAddress.cpp b/src/standards/Tizen/Contact/JSContactEmailAddress.cpp new file mode 100755 index 0000000..00c9d4a --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactEmailAddress.cpp @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactEmailAddress.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSContactEmailAddress class + */ + +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactEmailAddressTypeArray.h" +#include "JSContactEmailAddress.h" + +#define CONTACT_CLASS_NAME "EmailAddress" + +#define CONTACT_ATTR_EMAIL "email" +#define CONTACT_ATTR_TYPES "types" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassRef JSContactEmailAddress::m_classRef = NULL; + +JSClassDefinition JSContactEmailAddress::m_classInfo = +{ + 0, + kJSClassAttributeNone, + CONTACT_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticValue JSContactEmailAddress::m_property[] = { + { CONTACT_ATTR_EMAIL, getEmail, setEmail, kJSPropertyAttributeNone }, + { CONTACT_ATTR_TYPES, getTypes, setTypes, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactEmailAddress::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSContactEmailAddress::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSContactEmailAddress::createJSObject(JSContextRef context, + const std::string email, + const ContactEmailAddressTypeArrayPtr types) +{ + ContactEmailAddressPtr privateData = ContactEmailAddressPtr(new ContactEmailAddress()); + + privateData->setEmail(email); + privateData->setTypes(types); + + JSContactEmailAddressPriv *priv = new JSContactEmailAddressPriv(context, privateData); + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast(priv)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +bool JSContactEmailAddress::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactEmailAddressPtr JSContactEmailAddress::getContactEmailAddress(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactEmailAddressPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSContactEmailAddress::Initialize(JSContextRef context, JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSContactEmailAddress::Finalize(JSObjectRef object) +{ + //delete (JSObjectGetPrivate(object)); +} + +ContactEmailAddressPtr JSContactEmailAddress::getPrivData(JSObjectRef object) +{ + //LogDebug("entered"); + JSContactEmailAddressPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + ContactEmailAddressPtr result = priv->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + return result; +} + +JSValueRef JSContactEmailAddress::getEmail(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactEmailAddressPtr emailAddress = getPrivData(object); + return converter->toJSValueRef(emailAddress->getEmail()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactEmailAddress::setEmail(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactEmailAddressPtr emailAddress = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + emailAddress->setEmail(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + + +JSValueRef JSContactEmailAddress::getTypes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactEmailAddressPtr emailAddress = getPrivData(object); + return JSContactEmailAddressTypeArray::createArray(context, emailAddress->getTypes()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactEmailAddress::setTypes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactEmailAddressPtr emailAddress = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + + if(JSContactEmailAddressTypeArray::isObjectOfClass(context, value)) + emailAddress->setTypes(converter->toContactEmailAddressTypeArray(value)); // TODO to implement this function on converter + else + emailAddress->setTypes(JSContactEmailAddressTypeArray::getContactEmailAddressTypeArray(context, value)); + + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactEmailAddress.h b/src/standards/Tizen/Contact/JSContactEmailAddress.h new file mode 100755 index 0000000..dfd860c --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactEmailAddress.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactEmailAddress.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSContactEmailAddress class + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_EMAIL_ADDRESS_H_ +#define _TIZEN_CONTACT_JS_CONTACT_EMAIL_ADDRESS_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject JSContactEmailAddressPriv; + +class JSContactEmailAddress { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context, + const std::string email = "", + const TizenApis::Api::Contact::ContactEmailAddressTypeArrayPtr types = TizenApis::Api::Contact::ContactEmailAddressTypeArrayPtr(new TizenApis::Api::Contact::ContactEmailAddressTypeArray())); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactEmailAddressPtr getContactEmailAddress(JSContextRef context, JSValueRef value); + +private: + /** + * The callback invoked when an object is first created. + */ + static void Initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void Finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static TizenApis::Api::Contact::ContactEmailAddressPtr getPrivData(JSObjectRef object); + + static JSValueRef getEmail(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setEmail(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getTypes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setTypes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_EMAIL_ADDRESS_H_ diff --git a/src/standards/Tizen/Contact/JSContactEmailAddressArray.cpp b/src/standards/Tizen/Contact/JSContactEmailAddressArray.cpp new file mode 100755 index 0000000..e59d3c1 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactEmailAddressArray.cpp @@ -0,0 +1,589 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactEmailAddressArray.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactEmailAddressArray.h" + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassDefinition JSContactEmailAddressArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSContactEmailAddressArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactEmailAddressArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSContactEmailAddressArray::m_jsClassRef = JSClassCreate( + JSContactEmailAddressArray::getClassInfo()); + +JSValueRef JSContactEmailAddressArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + JSContactEmailAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactEmailAddressArrayPtr emailAddresses = priv->getObject(); + if (emailAddresses) { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + return converter->toJSValueRef(emailAddresses->size()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSContactEmailAddressArray::createArray(JSContextRef context, + const ContactEmailAddressArrayPtr &emailAddresses) +{ + JSContactEmailAddressArrayPriv *priv = new JSContactEmailAddressArrayPriv(context, emailAddresses); + return JSObjectMake(context, getClassRef(), priv); +} + +bool JSContactEmailAddressArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactEmailAddressArrayPtr JSContactEmailAddressArray::getContactEmailAddressArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactEmailAddressArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +const JSClassDefinition* JSContactEmailAddressArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSContactEmailAddressArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +void JSContactEmailAddressArray::initialize(JSContextRef context, + JSObjectRef object) +{ + //LogDebug("enter"); +} + +void JSContactEmailAddressArray::finalize(JSObjectRef object) +{ + //LogDebug("enter"); + JSContactEmailAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSContactEmailAddressArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactEmailAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactEmailAddressArrayPtr emailAddresses = priv->getObject(); + if (index < emailAddresses->size()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSContactEmailAddressArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactEmailAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactEmailAddressArrayPtr emailAddresses = priv->getObject(); + if (index < emailAddresses->size()) { + ContactEmailAddressPtr result = emailAddresses->at(index); + if (result) { + return converter->toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactEmailAddressArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + ContactEmailAddressPtr emailAddress; + if (!JSValueIsUndefined(context, value)) { + emailAddress = converter->toContactEmailAddress(value); + } + JSContactEmailAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactEmailAddressArrayPtr emailAddresses = priv->getObject(); + if (!emailAddresses) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (emailAddresses->size() <= index) { + emailAddresses->resize(index + 1); + } + (*emailAddresses)[index] = emailAddress; + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + } + return false; +} + +JSValueRef JSContactEmailAddressArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + ContactEmailAddressArrayPtr emailAddresses = ContactEmailAddressArrayPtr(new ContactEmailAddressArray()); + JSContactEmailAddressArrayPriv *newPrivateObject = new JSContactEmailAddressArrayPriv(context, emailAddresses); + JSValueRef result = JSObjectMake(context, getClassRef(), newPrivateObject); + + //copy current emailAddresses + JSContactEmailAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressArrayPtr currentEmailAddresses = priv->getObject(); + for (size_t i = 0; i < currentEmailAddresses->size(); ++i) { + emailAddresses->push_back(currentEmailAddresses->at(i)); + } + + //copy submitted arrays + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + emailAddresses->push_back(converter->toContactEmailAddress(att)); + } + } + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactEmailAddressArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactEmailAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressArrayPtr currentEmailAddresses = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentEmailAddresses->size(); ++i) { + if (i != 0) { + result += separator; + } + //FIXME : to be changed to support join + //result += currentEmailAddresses->at(i); + } + return converter->toJSValueRef(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactEmailAddressArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactEmailAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressArrayPtr currentEmailAddresses = priv->getObject(); + if (currentEmailAddresses->size() > 0) { + ContactEmailAddressPtr result = currentEmailAddresses->at( + currentEmailAddresses->size() - 1); + currentEmailAddresses->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactEmailAddressArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactEmailAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressArrayPtr currentEmailAddresses = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentEmailAddresses->push_back(converter->toContactEmailAddress(arguments[i])); + } + return converter->toJSValueRef(currentEmailAddresses->size()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactEmailAddressArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactEmailAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressArrayPtr currentEmailAddresses = priv->getObject(); + std::reverse(currentEmailAddresses->begin(), currentEmailAddresses->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactEmailAddressArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactEmailAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressArrayPtr currentEmailAddresses = priv->getObject(); + if (currentEmailAddresses->size() > 0) { + ContactEmailAddressPtr result = currentEmailAddresses->at(0); + currentEmailAddresses->erase(currentEmailAddresses->begin()); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactEmailAddressArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactEmailAddressArrayPtr emailAddresses = ContactEmailAddressArrayPtr(new ContactEmailAddressArray()); + JSContactEmailAddressArrayPriv *newPrivateObject = new JSContactEmailAddressArrayPriv( + context, + emailAddresses); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current emailAddresses + JSContactEmailAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressArrayPtr currentEmailAddresses = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentEmailAddresses->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentEmailAddresses->size()) { + last = currentEmailAddresses->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + emailAddresses->push_back(currentEmailAddresses->at(i)); + } + + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactEmailAddressArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactEmailAddressArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressArrayPtr currentEmailAddresses = priv->getObject(); + std::sort(currentEmailAddresses->begin(), currentEmailAddresses->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactEmailAddressArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactEmailAddressArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSContactEmailAddressArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactEmailAddressArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactEmailAddressArray.h b/src/standards/Tizen/Contact/JSContactEmailAddressArray.h new file mode 100755 index 0000000..2918159 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactEmailAddressArray.h @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactEmailAddressArray.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_EMAIL_ADDRESS_ARRAY_H_ +#define _TIZEN_CONTACT_JS_CONTACT_EMAIL_ADDRESS_ARRAY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSContactEmailAddressArrayPriv; + +class JSContactEmailAddressArray +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const TizenApis::Api::Contact::ContactEmailAddressArrayPtr &emailAddresses); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactEmailAddressArrayPtr getContactEmailAddressArray(JSContextRef context, JSValueRef value); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_EMAIL_ADDRESS_ARRAY_H_ diff --git a/src/standards/Tizen/Contact/JSContactEmailAddressTypeArray.cpp b/src/standards/Tizen/Contact/JSContactEmailAddressTypeArray.cpp new file mode 100755 index 0000000..baf2cd9 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactEmailAddressTypeArray.cpp @@ -0,0 +1,587 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactEmailAddressTypeArray.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactEmailAddressTypeArray.h" + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +JSClassDefinition JSContactEmailAddressTypeArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSContactEmailAddressTypeArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactEmailAddressTypeArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSContactEmailAddressTypeArray::m_jsClassRef = JSClassCreate( + JSContactEmailAddressTypeArray::getClassInfo()); + +JSValueRef JSContactEmailAddressTypeArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + JSContactEmailAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + ContactEmailAddressTypeArrayPtr typeArray = priv->getObject(); + if (typeArray) { + BasicConverter converter = BasicConverterFactory::getConverter(context); + return converter->toJSValueRef(typeArray->size()); + } + } + Catch(Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSContactEmailAddressTypeArray::createArray(JSContextRef context, + const ContactEmailAddressTypeArrayPtr &typeArray) +{ + JSContactEmailAddressTypeArrayPriv *priv = new JSContactEmailAddressTypeArrayPriv(context, typeArray); + return JSObjectMake(context, getClassRef(), priv); +} + +bool JSContactEmailAddressTypeArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactEmailAddressTypeArrayPtr JSContactEmailAddressTypeArray::getContactEmailAddressTypeArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(InvalidArgumentException); + } + JSContactEmailAddressTypeArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + return priv->getObject(); +} + +const JSClassDefinition* JSContactEmailAddressTypeArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSContactEmailAddressTypeArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +void JSContactEmailAddressTypeArray::initialize(JSContextRef context, + JSObjectRef object) +{ + //LogDebug("enter"); +} + +void JSContactEmailAddressTypeArray::finalize(JSObjectRef object) +{ + //LogDebug("enter"); + JSContactEmailAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSContactEmailAddressTypeArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + //LogDebug("enter"); + BasicConverter converter = BasicConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactEmailAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + ContactEmailAddressTypeArrayPtr typeArray = priv->getObject(); + if (index < typeArray->size()) { + return true; + } + } + Catch(Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSContactEmailAddressTypeArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactEmailAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + ContactEmailAddressTypeArrayPtr typeArray = priv->getObject(); + if (index < typeArray->size()) { + std::string result = converter->toContactEmailAddressTypeStr(typeArray->at(index)); + if (!result.empty()) { + return converter->toJSValueRef(result); + } + } + } + Catch(Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactEmailAddressTypeArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + std::string str; + if (!JSValueIsUndefined(context, value)) { + str = converter->toString(value); + } + JSContactEmailAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(NullPointerException); + } + ContactEmailAddressTypeArrayPtr typeArray = priv->getObject(); + if (!typeArray) { + Throw(NullPointerException); + } + if (typeArray->size() <= index) { + typeArray->resize(index + 1); + } + (*typeArray)[index] = converter->toContactEmailAddressType(str); + return true; + } + Catch(Exception) + { + LogError("error occured"); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + } + return false; +} + +JSValueRef JSContactEmailAddressTypeArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + ContactEmailAddressTypeArrayPtr typeArray = ContactEmailAddressTypeArrayPtr(new ContactEmailAddressTypeArray()); + JSContactEmailAddressTypeArrayPriv *newPrivateObject = new JSContactEmailAddressTypeArrayPriv( + context, + typeArray); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current typeArray + JSContactEmailAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressTypeArrayPtr currentStrings = priv->getObject(); + for (size_t i = 0; i < currentStrings->size(); ++i) { + typeArray->push_back(currentStrings->at(i)); + } + + //copy submitted arrays + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + typeArray->push_back(converter->toContactEmailAddressType(att)); + } + } + return result; + } + Catch(Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactEmailAddressTypeArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + BasicConverter converter = BasicConverterFactory::getConverter(context); + JSContactEmailAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressTypeArrayPtr currentStrings = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentStrings->size(); ++i) { + if (i != 0) { + result += separator; + } + result += currentStrings->at(i); + } + return converter->toJSValueRef(result); + } + Catch(Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactEmailAddressTypeArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactEmailAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressTypeArrayPtr currentStrings = priv->getObject(); + if (currentStrings->size() > 0) { + std::string result = converter->toContactEmailAddressTypeStr(currentStrings->at(currentStrings->size() - 1)); + currentStrings->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactEmailAddressTypeArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactEmailAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressTypeArrayPtr currentStrings = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentStrings->push_back(converter->toContactEmailAddressType(arguments[i])); + } + return converter->toJSValueRef(currentStrings->size()); + } + Catch(Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactEmailAddressTypeArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + Converter converter(context); + JSContactEmailAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressTypeArrayPtr currentStrings = priv->getObject(); + std::reverse(currentStrings->begin(), currentStrings->end()); + return thisObject; + } + Catch(Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactEmailAddressTypeArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactEmailAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressTypeArrayPtr currentStrings = priv->getObject(); + if (currentStrings->size() > 0) { + std::string result = converter->toContactEmailAddressTypeStr(currentStrings->at(0)); + currentStrings->erase(currentStrings->begin()); + return converter->toJSValueRef(result); + } + } + Catch(Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactEmailAddressTypeArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + BasicConverter converter = BasicConverterFactory::getConverter(context); + ContactEmailAddressTypeArrayPtr typeArray = ContactEmailAddressTypeArrayPtr(new ContactEmailAddressTypeArray()); + JSContactEmailAddressTypeArrayPriv *newPrivateObject = new JSContactEmailAddressTypeArrayPriv( + context, + typeArray); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current typeArray + JSContactEmailAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressTypeArrayPtr currentStrings = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentStrings->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentStrings->size()) { + last = currentStrings->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + typeArray->push_back(currentStrings->at(i)); + } + + return result; + } + Catch(Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactEmailAddressTypeArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + BasicConverter converter = BasicConverterFactory::getConverter(context); + JSContactEmailAddressTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactEmailAddressTypeArrayPtr currentStrings = priv->getObject(); + std::sort(currentStrings->begin(), currentStrings->end()); + return thisObject; + } + Catch(Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactEmailAddressTypeArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactEmailAddressTypeArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSContactEmailAddressTypeArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactEmailAddressTypeArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactEmailAddressTypeArray.h b/src/standards/Tizen/Contact/JSContactEmailAddressTypeArray.h new file mode 100755 index 0000000..6dbee64 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactEmailAddressTypeArray.h @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactEmailAddressTypeArray.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_EMAIL_ADDRESS_TYPE_ARRAY_H_ +#define _TIZEN_CONTACT_JS_CONTACT_EMAIL_ADDRESS_TYPE_ARRAY_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSContactEmailAddressTypeArrayPriv; + +class JSContactEmailAddressTypeArray +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const TizenApis::Api::Contact::ContactEmailAddressTypeArrayPtr &Strings); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactEmailAddressTypeArrayPtr getContactEmailAddressTypeArray(JSContextRef context, JSValueRef value); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_EMAIL_ADDRESS_TYPE_ARRAY_H_ diff --git a/src/standards/Tizen/Contact/JSContactManager.cpp b/src/standards/Tizen/Contact/JSContactManager.cpp new file mode 100755 index 0000000..7cb1739 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactManager.cpp @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactManager.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.3 + * @brief + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "plugin_config.h" +#include "ContactManagerController.h" +#include "ContactConverter.h" +#include "JSContactManager.h" + +#define TIZEN_CONTACT_MANAGER_DEVICE_ADDRESS_BOOK "DEVICE_ADDRESS_BOOK" +#define TIZEN_CONTACT_MANAGER_PHONE_ADDRESS_BOOK "PHONE_ADDRESS_BOOK" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +JSClassDefinition JSContactManager::m_classInfo = { + 0, + kJSClassAttributeNone, + "ContactManager", + 0, + m_property, + m_function, + Initialize, + Finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +const JSClassDefinition* JSContactManager::getClassInfo() +{ + return &m_classInfo; +} + +JSStaticValue JSContactManager::m_property[] = { + { TIZEN_CONTACT_MANAGER_DEVICE_ADDRESS_BOOK, getConstProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_CONTACT_MANAGER_PHONE_ADDRESS_BOOK, getConstProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactManager::m_function[] = { + { "getAddressBooks", getAddressBooks, kJSPropertyAttributeNone }, + { "getDefaultAddressBook", getDefaultAddressBook, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSContactManager::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSClassRef JSContactManager::m_classRef = JSClassCreate(JSContactManager::getClassInfo()); + +void JSContactManager::Initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("Entered"); + IContactManagerPtr contactManager = ContactFactory::getInstance().createContactManager(); + + ContactManagerController *priv = new ContactManagerController(context, contactManager); + + JSObjectSetPrivate(object, static_cast(priv)); +} + +void JSContactManager::Finalize(JSObjectRef object) +{ + LogDebug("entered"); + ContactManagerController *priv = static_cast(JSObjectGetPrivate(object)); + LogInfo("Delete address book manager"); + delete priv; +} + +JSValueRef JSContactManager::getConstProperty(JSContextRef context, + JSObjectRef object, + JSStringRef jsPropertyName, + JSValueRef* exception) +{ + BasicConverter converter = BasicConverterFactory::getConverter(context); + + Try { + std::string propertyName = converter->toString(jsPropertyName); + if (propertyName == TIZEN_CONTACT_MANAGER_DEVICE_ADDRESS_BOOK) { + return converter->toJSValueRef(DEVICE_ADDRESS_BOOK); + } else if (propertyName == TIZEN_CONTACT_MANAGER_PHONE_ADDRESS_BOOK) { + return converter->toJSValueRef(PHONE_ADDRESS_BOOK); + } + } Catch(Exception) { + LogError("error during getting property"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactManager::getAddressBooks(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + IContactManagerPtr contactManager; + JSContextRef gContext; + ContactManagerController *controller; + + Try { + controller = static_cast(JSObjectGetPrivate(thisObject)); + if (!controller) { + ThrowMsg(InvalidArgumentException, "No private object."); + } + contactManager = controller->getObject(); + gContext = controller->getContext(); + } Catch(Exception) { + LogError("No private object"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong object"); + } + + AceSecurityStatus status = CONTACT_CHECK_ACCESS(controller->getContext(), CONTACT_FUNCTION_API_GET_ADDRESS_BOOKS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + BasicValidator validator = BasicValidatorFactory::getValidator(context, exception); + Try { + if (argumentCount < 1 || argumentCount > 2) + ThrowMsg(InvalidArgumentException, "Wrong arguments count."); + + if (!validator->isCallback(arguments[0])) + ThrowMsg(InvalidArgumentException, "1st argument is not function."); + + if (argumentCount >= 2) + { + if (!validator->isCallback(arguments[1])) + ThrowMsg(InvalidArgumentException, "2nd argument is not function."); + } + + } Catch(Exception ) { + LogError("Argument type mismatch : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + + callbackManager->setOnSuccess(arguments[0]); + + if(argumentCount >= 2) + callbackManager->setOnError(arguments[1]); + + EventContactManagerGetAddressBooksPtr dplEvent(new EventContactManagerGetAddressBooks()); + + // set event handler's data + dplEvent->setPrivateData(DPL::StaticPointerCast(callbackManager)); + dplEvent->setForAsynchronousCall(controller); + + //DPL::SharedPtr eventContr = DPL::StaticPointerCast< IEventController>(dplEvent); + //ContactManagerGetAddressBooksPendingOperation *gcPendingOperation = new ContactManagerGetAddressBooksPendingOperation(eventContr); + + Try { + contactManager->getAddressBooks(dplEvent); + } Catch(Exception) { + LogError("Error on platform : " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + //return JSObjectMake(gContext, JSPendingOperation::getClassRef(), gcPendingOperation); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactManager::getDefaultAddressBook(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + ContactManagerController *priv = + static_cast(JSObjectGetPrivate(thisObject)); + if (!priv) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong object"); + } + + AceSecurityStatus status = CONTACT_CHECK_ACCESS(priv->getContext(), CONTACT_FUNCTION_API_GET_DEFAULT_ADDRESS_BOOK); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + IContactManagerPtr contactManager; + JSContextRef gContext; + Try { + contactManager = priv->getObject(); + gContext = priv->getContext(); + } Catch(Exception) { + LogError("contact manager or context is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong object"); + } + + BasicValidator validator = BasicValidatorFactory::getValidator(context, exception); + if (argumentCount > 0) { + /* Argument count must be 0. */ + LogError("TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Wrong arguments"); + } + + IAddressBookPtr defaultAddressBook; + Try { + defaultAddressBook = contactManager->getDefaultAddressBook(); + } Catch(Exception){ + LogError("Internal error."); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + JSValueRef resultValue; + Try { + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(gContext); + resultValue = converter->toJSValueRef(defaultAddressBook); + } Catch(Exception){ + LogError("Conversion error."); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Internal error"); + } + + return resultValue; +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactManager.h b/src/standards/Tizen/Contact/JSContactManager.h new file mode 100755 index 0000000..414770d --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactManager.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactManager.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_MANAGER_H_ +#define _TIZEN_CONTACT_JS_CONTACT_MANAGER_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +class JSContactManager +{ +public: + static const JSClassDefinition* getClassInfo(); + + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + +private: + /** + * The callback invoked when an object is first created. + */ + static void Initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void Finalize(JSObjectRef object); + + /** + * Getter for const properties + */ + static JSValueRef getConstProperty(JSContextRef context, + JSObjectRef object, + JSStringRef jsPropertyName, + JSValueRef* exception); + + /** + * Get Address Books. + */ + static JSValueRef getAddressBooks(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Get Default Address Books. + */ + static JSValueRef getDefaultAddressBook(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_classRef; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif //_TIZEN_CONTACT_JS_CONTACT_MANAGER_H_ diff --git a/src/standards/Tizen/Contact/JSContactName.cpp b/src/standards/Tizen/Contact/JSContactName.cpp new file mode 100755 index 0000000..ea45286 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactName.cpp @@ -0,0 +1,480 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactName.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSContactName class + */ + +#include +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactName.h" + +#define CONTACT_CLASS_NAME "ContactName" +#define CONTACT_PROP_ATTR_PREFIX "prefix" +#define CONTACT_PROP_ATTR_FIRST_NAME "firstName" +#define CONTACT_PROP_ATTR_MIDDLE_NAME "middleName" +#define CONTACT_PROP_ATTR_LAST_NAME "lastName" +#define CONTACT_PROP_ATTR_NICKNAMES "nicknames" +#define CONTACT_PROP_ATTR_PHONETIC_NAME "phoneticName" +#define CONTACT_PROP_ATTR_DISPLAY_NAME "displayName" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassRef JSContactName::m_classRef = NULL; + +JSClassDefinition JSContactName::m_classInfo = +{ + 0, + kJSClassAttributeNone, + CONTACT_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticValue JSContactName::m_property[] = { + { CONTACT_PROP_ATTR_PREFIX, getPrefix, setPrefix, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_FIRST_NAME, getFirstName, setFirstName, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_MIDDLE_NAME, getMiddleName, setMiddleName, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_LAST_NAME, getLastName, setLastName, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_NICKNAMES, getNicknames, setNicknames, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_PHONETIC_NAME, getPhoneticName, setPhoneticName, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_DISPLAY_NAME, getDisplayName, setDisplayName, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactName::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSContactName::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSContactName::createJSObject(JSContextRef context, + const std::string& prefix, + const std::string& firstName, + const std::string& middleName, + const std::string& lastName, + const StringArrayPtr& nicknames, + const std::string& phoneticName, + const std::string& displayName) +{ + ContactNamePtr privateData = ContactNamePtr(new ContactName()); + privateData->setPrefix(prefix); + privateData->setFirstName(firstName); + privateData->setMiddleName(middleName); + privateData->setLastName(lastName); + privateData->setNicknames(nicknames); + privateData->setPhoneticName(phoneticName); + privateData->setDisplayName(displayName); + JSContactNamePriv *priv = new JSContactNamePriv(context, privateData); + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast(priv)); + if (NULL == jsValueRef) + { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +bool JSContactName::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactNamePtr JSContactName::getContactName(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + JSContactNamePriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + + return priv->getObject(); +} + +void JSContactName::Initialize(JSContextRef context, JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSContactName::Finalize(JSObjectRef object) +{ + //delete (JSObjectGetPrivate(object)); +} + +ContactNamePtr JSContactName::getPrivData(JSObjectRef object) +{ + //LogDebug("entered"); + JSContactNamePriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + + ContactNamePtr result = priv->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + + return result; +} + +JSValueRef JSContactName::getPrefix(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactNamePtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getPrefix()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactName::setPrefix(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactNamePtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setPrefix(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactName::getFirstName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactNamePtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getFirstName()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactName::setFirstName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactNamePtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setFirstName(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactName::getMiddleName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactNamePtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getMiddleName()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactName::setMiddleName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactNamePtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setMiddleName(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactName::getLastName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactNamePtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getLastName()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactName::setLastName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactNamePtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setLastName(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactName::getNicknames(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactNamePtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getNicknames()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactName::setNicknames(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactNamePtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setNicknames(converter->toStringArray(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactName::getPhoneticName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactNamePtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getPhoneticName()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactName::setPhoneticName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactNamePtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setPhoneticName(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactName::getDisplayName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactNamePtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getDisplayName()); + } + Catch(WrtDeviceApis::Commons::Exception){ + LogWarning("trying to get incorrect value"); +} + return JSValueMakeUndefined(context); +} + +bool JSContactName::setDisplayName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactNamePtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setDisplayName(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactName.h b/src/standards/Tizen/Contact/JSContactName.h new file mode 100755 index 0000000..697063b --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactName.h @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactName.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSContactName class + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_NAME_H_ +#define _TIZEN_CONTACT_JS_CONTACT_NAME_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject JSContactNamePriv; + +class JSContactName { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context, + const std::string& prefix, + const std::string& firstName, + const std::string& middleName, + const std::string& lastName, + const TizenApis::Api::Contact::StringArrayPtr& nicknames, + const std::string& phoneticName, + const std::string& displayName); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactNamePtr getContactName(JSContextRef context, JSValueRef value); + +private: + /** + * The callback invoked when an object is first created. + */ + static void Initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void Finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static TizenApis::Api::Contact::ContactNamePtr getPrivData(JSObjectRef object); + + static JSValueRef getPrefix(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setPrefix(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getFirstName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setFirstName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getMiddleName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setMiddleName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getLastName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setLastName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getNicknames(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setNicknames(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getPhoneticName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setPhoneticName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getDisplayName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setDisplayName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_NAME_H_ diff --git a/src/standards/Tizen/Contact/JSContactOrganization.cpp b/src/standards/Tizen/Contact/JSContactOrganization.cpp new file mode 100755 index 0000000..33262dd --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactOrganization.cpp @@ -0,0 +1,416 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactOrganization.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSContactOrganization class + */ + +#include "JSContactOrganization.h" +#include +#include +#include +#include +#include "ContactConverter.h" + +#define ORGANIZATION_CLASS_NAME "ContactOrganization" + +#define CONTACT_ATTR_NAME "name" +#define CONTACT_ATTR_DEPARTMENT "department" +#define CONTACT_ATTR_OFFICE "office" +#define CONTACT_ATTR_TITLE "title" +#define CONTACT_ATTR_ROLE "role" +#define CONTACT_ATTR_LOGO_URI "logoURI" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassRef JSContactOrganization::m_classRef = NULL; + +JSClassDefinition JSContactOrganization::m_classInfo = +{ + 0, + kJSClassAttributeNone, + ORGANIZATION_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticValue JSContactOrganization::m_property[] = { + { CONTACT_ATTR_NAME, getName, setName, kJSPropertyAttributeNone }, + { CONTACT_ATTR_DEPARTMENT, getDepartment, setDepartment, kJSPropertyAttributeNone }, + { CONTACT_ATTR_OFFICE, getOffice, setOffice, kJSPropertyAttributeNone }, + { CONTACT_ATTR_TITLE, getTitle, setTitle, kJSPropertyAttributeNone }, + { CONTACT_ATTR_ROLE, getRole, setRole, kJSPropertyAttributeNone }, + { CONTACT_ATTR_LOGO_URI, getLogoURI, setLogoURI, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactOrganization::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSContactOrganization::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSContactOrganization::createJSObject(JSContextRef context, + const std::string& name, + const std::string& department, + const std::string& office, + const std::string& title, + const std::string& role, + const std::string& logoURI) +{ + ContactOrganizationPtr privateData = ContactOrganizationPtr(new ContactOrganization()); + privateData->setName(name); + privateData->setDepartment(department); + privateData->setOffice(office); + privateData->setTitle(title); + privateData->setRole(role); + privateData->setLogoURI(logoURI); + JSContactOrganizationPriv *priv = new JSContactOrganizationPriv(context, privateData); + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast(priv)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +bool JSContactOrganization::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactOrganizationPtr JSContactOrganization::getContactOrganization(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactOrganizationPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSContactOrganization::Initialize(JSContextRef context, JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSContactOrganization::Finalize(JSObjectRef object) +{ + //delete (JSObjectGetPrivate(object)); +} + +ContactOrganizationPtr JSContactOrganization::getPrivData(JSObjectRef object) +{ + //LogDebug("entered"); + JSContactOrganizationPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + ContactOrganizationPtr result = priv->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + return result; +} + +JSValueRef JSContactOrganization::getName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactOrganizationPtr organization = getPrivData(object); + return converter->toJSValueRef(organization->getName()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactOrganization::setName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactOrganizationPtr organization = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + organization->setName(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + + +JSValueRef JSContactOrganization::getDepartment(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactOrganizationPtr organization = getPrivData(object); + return converter->toJSValueRef(organization->getDepartment()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactOrganization::setDepartment(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactOrganizationPtr organization = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + organization->setDepartment(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactOrganization::getOffice(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactOrganizationPtr organization = getPrivData(object); + return converter->toJSValueRef(organization->getOffice()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactOrganization::setOffice(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactOrganizationPtr organization = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + organization->setOffice(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactOrganization::getTitle(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactOrganizationPtr organization = getPrivData(object); + return converter->toJSValueRef(organization->getTitle()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactOrganization::setTitle(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactOrganizationPtr organization = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + organization->setTitle(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactOrganization::getRole(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactOrganizationPtr organization = getPrivData(object); + return converter->toJSValueRef(organization->getRole()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactOrganization::setRole(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactOrganizationPtr organization = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + organization->setRole(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactOrganization::getLogoURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactOrganizationPtr organization = getPrivData(object); + return converter->toJSValueRef(organization->getLogoURI()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactOrganization::setLogoURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactOrganizationPtr organization = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + organization->setLogoURI(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactOrganization.h b/src/standards/Tizen/Contact/JSContactOrganization.h new file mode 100755 index 0000000..0aa8092 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactOrganization.h @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactOrganization.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSContactOrganization class + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_ORGANIZATION_H_ +#define _TIZEN_CONTACT_JS_CONTACT_ORGANIZATION_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject JSContactOrganizationPriv; + +class JSContactOrganization { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context, + const std::string& name, + const std::string& department, + const std::string& office, + const std::string& title, + const std::string& role, + const std::string& logoURI); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactOrganizationPtr getContactOrganization(JSContextRef context, JSValueRef value); + +private: + /** + * The callback invoked when an object is first created. + */ + static void Initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void Finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static TizenApis::Api::Contact::ContactOrganizationPtr getPrivData(JSObjectRef object); + + static JSValueRef getName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getDepartment(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setDepartment(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getOffice(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setOffice(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getTitle(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setTitle(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getRole(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setRole(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getLogoURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setLogoURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_ORGANIZATION_H_ diff --git a/src/standards/Tizen/Contact/JSContactOrganizationArray.cpp b/src/standards/Tizen/Contact/JSContactOrganizationArray.cpp new file mode 100755 index 0000000..6307a80 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactOrganizationArray.cpp @@ -0,0 +1,588 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactOrganizationArray.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactOrganizationArray.h" + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassDefinition JSContactOrganizationArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSContactOrganizationArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactOrganizationArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSContactOrganizationArray::m_jsClassRef = JSClassCreate( + JSContactOrganizationArray::getClassInfo()); + +JSValueRef JSContactOrganizationArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + JSContactOrganizationArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactOrganizationArrayPtr organizations = priv->getObject(); + if (organizations) { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + return converter->toJSValueRef(organizations->size()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSContactOrganizationArray::createArray(JSContextRef context, + const ContactOrganizationArrayPtr &organizations) +{ + JSContactOrganizationArrayPriv *priv = new JSContactOrganizationArrayPriv(context, organizations); + return JSObjectMake(context, getClassRef(), priv); +} + +bool JSContactOrganizationArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactOrganizationArrayPtr JSContactOrganizationArray::getContactOrganizationArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactOrganizationArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} +const JSClassDefinition* JSContactOrganizationArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSContactOrganizationArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +void JSContactOrganizationArray::initialize(JSContextRef context, + JSObjectRef object) +{ + //LogDebug("enter"); +} + +void JSContactOrganizationArray::finalize(JSObjectRef object) +{ + //LogDebug("enter"); + JSContactOrganizationArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSContactOrganizationArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactOrganizationArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactOrganizationArrayPtr organizations = priv->getObject(); + if (index < organizations->size()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSContactOrganizationArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactOrganizationArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactOrganizationArrayPtr organizations = priv->getObject(); + if (index < organizations->size()) { + ContactOrganizationPtr result = organizations->at(index); + if (result) { + return converter->toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactOrganizationArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + ContactOrganizationPtr organization; + if (!JSValueIsUndefined(context, value)) { + organization = converter->toContactOrganization(value); + } + JSContactOrganizationArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactOrganizationArrayPtr organizations = priv->getObject(); + if (!organizations) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (organizations->size() <= index) { + organizations->resize(index + 1); + } + (*organizations)[index] = organization; + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + } + return false; +} + +JSValueRef JSContactOrganizationArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + ContactOrganizationArrayPtr organizations = ContactOrganizationArrayPtr(new ContactOrganizationArray()); + JSContactOrganizationArrayPriv *newPrivateObject = new JSContactOrganizationArrayPriv(context, organizations); + JSValueRef result = JSObjectMake(context, getClassRef(), newPrivateObject); + + //copy current organizations + JSContactOrganizationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactOrganizationArrayPtr currentOrganizations = priv->getObject(); + for (size_t i = 0; i < currentOrganizations->size(); ++i) { + organizations->push_back(currentOrganizations->at(i)); + } + + //copy submitted arrays + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + organizations->push_back(converter->toContactOrganization(att)); + } + } + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactOrganizationArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactOrganizationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactOrganizationArrayPtr currentOrganizations = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentOrganizations->size(); ++i) { + if (i != 0) { + result += separator; + } + //FIXME : to be changed to support join + //result += currentOrganizations->at(i); + } + return converter->toJSValueRef(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactOrganizationArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactOrganizationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactOrganizationArrayPtr currentOrganizations = priv->getObject(); + if (currentOrganizations->size() > 0) { + ContactOrganizationPtr result = currentOrganizations->at( + currentOrganizations->size() - 1); + currentOrganizations->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactOrganizationArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactOrganizationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactOrganizationArrayPtr currentOrganizations = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentOrganizations->push_back(converter->toContactOrganization(arguments[i])); + } + return converter->toJSValueRef(currentOrganizations->size()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactOrganizationArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactOrganizationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactOrganizationArrayPtr currentOrganizations = priv->getObject(); + std::reverse(currentOrganizations->begin(), currentOrganizations->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactOrganizationArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactOrganizationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactOrganizationArrayPtr currentOrganizations = priv->getObject(); + if (currentOrganizations->size() > 0) { + ContactOrganizationPtr result = currentOrganizations->at(0); + currentOrganizations->erase(currentOrganizations->begin()); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactOrganizationArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactOrganizationArrayPtr organizations = ContactOrganizationArrayPtr(new ContactOrganizationArray()); + JSContactOrganizationArrayPriv *newPrivateObject = new JSContactOrganizationArrayPriv( + context, + organizations); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current organizations + JSContactOrganizationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactOrganizationArrayPtr currentOrganizations = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentOrganizations->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentOrganizations->size()) { + last = currentOrganizations->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + organizations->push_back(currentOrganizations->at(i)); + } + + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactOrganizationArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactOrganizationArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactOrganizationArrayPtr currentOrganizations = priv->getObject(); + std::sort(currentOrganizations->begin(), currentOrganizations->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactOrganizationArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactOrganizationArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSContactOrganizationArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactOrganizationArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactOrganizationArray.h b/src/standards/Tizen/Contact/JSContactOrganizationArray.h new file mode 100755 index 0000000..574bd30 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactOrganizationArray.h @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactOrganizationArray.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_ORGANIZATION_ARRAY_H_ +#define _TIZEN_CONTACT_JS_CONTACT_ORGANIZATION_ARRAY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSContactOrganizationArrayPriv; + +class JSContactOrganizationArray +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const TizenApis::Api::Contact::ContactOrganizationArrayPtr &organizations); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactOrganizationArrayPtr getContactOrganizationArray(JSContextRef context, JSValueRef value); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_ORGANIZATION_ARRAY_H_ diff --git a/src/standards/Tizen/Contact/JSContactPhoneNumber.cpp b/src/standards/Tizen/Contact/JSContactPhoneNumber.cpp new file mode 100755 index 0000000..912f02d --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactPhoneNumber.cpp @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactPhoneNumber.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSContactPhoneNumber class + */ + +#include +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactPhoneNumberTypeArray.h" +#include "JSContactPhoneNumber.h" + +#define FILTER_CLASS_NAME "ContactPhoneNumber" + +#define CONTACT_ATTR_NUMBER "number" +#define CONTACT_ATTR_TYPES "types" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassRef JSContactPhoneNumber::m_classRef = NULL; + +JSClassDefinition JSContactPhoneNumber::m_classInfo = +{ + 0, + kJSClassAttributeNone, + FILTER_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticValue JSContactPhoneNumber::m_property[] = { + { CONTACT_ATTR_NUMBER, getNumber, setNumber, kJSPropertyAttributeNone }, + { CONTACT_ATTR_TYPES, getTypes, setTypes, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactPhoneNumber::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSContactPhoneNumber::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSContactPhoneNumber::createJSObject(JSContextRef context + // FIXME + ) +{ + ContactPhoneNumberPtr privateData = ContactPhoneNumberPtr(new ContactPhoneNumber()); + JSContactPhoneNumberPriv *priv = new JSContactPhoneNumberPriv(context, privateData); + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast(priv)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +bool JSContactPhoneNumber::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactPhoneNumberPtr JSContactPhoneNumber::getContactPhoneNumber(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactPhoneNumberPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSContactPhoneNumber::Initialize(JSContextRef context, JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSContactPhoneNumber::Finalize(JSObjectRef object) +{ + //delete (JSObjectGetPrivate(object)); +} + +ContactPhoneNumberPtr JSContactPhoneNumber::getPrivData(JSObjectRef object) +{ + //LogDebug("entered"); + JSContactPhoneNumberPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + ContactPhoneNumberPtr result = priv->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + return result; +} + +JSValueRef JSContactPhoneNumber::getNumber(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPhoneNumberPtr contactPhoneNumber = getPrivData(object); + return converter->toJSValueRef(contactPhoneNumber->getNumber()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactPhoneNumber::setNumber(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPhoneNumberPtr contactPhoneNumber = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactPhoneNumber->setNumber(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + + +JSValueRef JSContactPhoneNumber::getTypes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPhoneNumberPtr contactPhoneNumber = getPrivData(object); + //return JSContactPhoneNumberTypeArray::createArray(context, contactPhoneNumber->getTypes()); + return converter->toJSValueRef(contactPhoneNumber->getTypes()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactPhoneNumber::setTypes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPhoneNumberPtr contactPhoneNumber = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + + if(JSContactPhoneNumberTypeArray::isObjectOfClass(context, value)) { + contactPhoneNumber->setTypes(converter->toStringArray(value)); + //contactPhoneNumber->setTypes(converter->toContactPhoneNumberTypeArray(value)); // TODO to implement this function on converter + } else { + contactPhoneNumber->setTypes(converter->toStringArray(value)); +// contactPhoneNumber->setTypes(JSContactPhoneNumberTypeArray::getContactPhoneNumberTypeArray(context, value)); + } + + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactPhoneNumber.h b/src/standards/Tizen/Contact/JSContactPhoneNumber.h new file mode 100755 index 0000000..8e8abf0 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactPhoneNumber.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactPhoneNumber.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSContactPhoneNumber class + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_PHONE_NUMBER_H_ +#define _TIZEN_CONTACT_JS_CONTACT_PHONE_NUMBER_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject JSContactPhoneNumberPriv; + +class JSContactPhoneNumber { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context + // FIXME fix this value + ); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactPhoneNumberPtr getContactPhoneNumber(JSContextRef context, JSValueRef value); + +private: + /** + * The callback invoked when an object is first created. + */ + static void Initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void Finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static TizenApis::Api::Contact::ContactPhoneNumberPtr getPrivData(JSObjectRef object); + + static JSValueRef getNumber(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setNumber(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getTypes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setTypes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_PHONE_NUMBER_H_ diff --git a/src/standards/Tizen/Contact/JSContactPhoneNumberArray.cpp b/src/standards/Tizen/Contact/JSContactPhoneNumberArray.cpp new file mode 100755 index 0000000..203bee6 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactPhoneNumberArray.cpp @@ -0,0 +1,589 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactPhoneNumberArray.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactPhoneNumberArray.h" + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassDefinition JSContactPhoneNumberArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSContactPhoneNumberArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactPhoneNumberArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSContactPhoneNumberArray::m_jsClassRef = JSClassCreate( + JSContactPhoneNumberArray::getClassInfo()); + +JSValueRef JSContactPhoneNumberArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + JSContactPhoneNumberArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactPhoneNumberArrayPtr contactPhoneNumbers = priv->getObject(); + if (contactPhoneNumbers) { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + return converter->toJSValueRef(contactPhoneNumbers->size()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSContactPhoneNumberArray::createArray(JSContextRef context, + const ContactPhoneNumberArrayPtr &contactPhoneNumbers) +{ + JSContactPhoneNumberArrayPriv *priv = new JSContactPhoneNumberArrayPriv(context, contactPhoneNumbers); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSContactPhoneNumberArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSContactPhoneNumberArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +bool JSContactPhoneNumberArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactPhoneNumberArrayPtr JSContactPhoneNumberArray::getContactPhoneNumberArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactPhoneNumberArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSContactPhoneNumberArray::initialize(JSContextRef context, + JSObjectRef object) +{ + //LogDebug("enter"); +} + +void JSContactPhoneNumberArray::finalize(JSObjectRef object) +{ + //LogDebug("enter"); + JSContactPhoneNumberArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSContactPhoneNumberArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactPhoneNumberArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactPhoneNumberArrayPtr contactPhoneNumbers = priv->getObject(); + if (index < contactPhoneNumbers->size()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSContactPhoneNumberArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactPhoneNumberArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactPhoneNumberArrayPtr contactPhoneNumbers = priv->getObject(); + if (index < contactPhoneNumbers->size()) { + ContactPhoneNumberPtr result = contactPhoneNumbers->at(index); + if (result) { + return converter->toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactPhoneNumberArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + ContactPhoneNumberPtr contactPhoneNumber; + if (!JSValueIsUndefined(context, value)) { + contactPhoneNumber = converter->toContactPhoneNumber(value); + } + JSContactPhoneNumberArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactPhoneNumberArrayPtr contactPhoneNumbers = priv->getObject(); + if (!contactPhoneNumbers) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (contactPhoneNumbers->size() <= index) { + contactPhoneNumbers->resize(index + 1); + } + (*contactPhoneNumbers)[index] = contactPhoneNumber; + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + } + return false; +} + +JSValueRef JSContactPhoneNumberArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + ContactPhoneNumberArrayPtr contactPhoneNumbers = ContactPhoneNumberArrayPtr(new ContactPhoneNumberArray()); + JSContactPhoneNumberArrayPriv *newPrivateObject = new JSContactPhoneNumberArrayPriv(context, contactPhoneNumbers); + JSValueRef result = JSObjectMake(context, getClassRef(), newPrivateObject); + + //copy current contactPhoneNumbers + JSContactPhoneNumberArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberArrayPtr currentContactPhoneNumbers = priv->getObject(); + for (size_t i = 0; i < currentContactPhoneNumbers->size(); ++i) { + contactPhoneNumbers->push_back(currentContactPhoneNumbers->at(i)); + } + + //copy submitted arrays + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + contactPhoneNumbers->push_back(converter->toContactPhoneNumber(att)); + } + } + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactPhoneNumberArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactPhoneNumberArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberArrayPtr currentContactPhoneNumbers = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentContactPhoneNumbers->size(); ++i) { + if (i != 0) { + result += separator; + } + //FIXME : to be changed to support join + //result += currentContactPhoneNumbers->at(i); + } + return converter->toJSValueRef(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactPhoneNumberArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactPhoneNumberArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberArrayPtr currentContactPhoneNumbers = priv->getObject(); + if (currentContactPhoneNumbers->size() > 0) { + ContactPhoneNumberPtr result = currentContactPhoneNumbers->at( + currentContactPhoneNumbers->size() - 1); + currentContactPhoneNumbers->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactPhoneNumberArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactPhoneNumberArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberArrayPtr currentContactPhoneNumbers = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentContactPhoneNumbers->push_back(converter->toContactPhoneNumber(arguments[i])); + } + return converter->toJSValueRef(currentContactPhoneNumbers->size()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactPhoneNumberArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactPhoneNumberArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberArrayPtr currentContactPhoneNumbers = priv->getObject(); + std::reverse(currentContactPhoneNumbers->begin(), currentContactPhoneNumbers->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactPhoneNumberArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactPhoneNumberArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberArrayPtr currentContactPhoneNumbers = priv->getObject(); + if (currentContactPhoneNumbers->size() > 0) { + ContactPhoneNumberPtr result = currentContactPhoneNumbers->at(0); + currentContactPhoneNumbers->erase(currentContactPhoneNumbers->begin()); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactPhoneNumberArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPhoneNumberArrayPtr contactPhoneNumbers = ContactPhoneNumberArrayPtr(new ContactPhoneNumberArray()); + JSContactPhoneNumberArrayPriv *newPrivateObject = new JSContactPhoneNumberArrayPriv( + context, + contactPhoneNumbers); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current contactPhoneNumbers + JSContactPhoneNumberArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberArrayPtr currentContactPhoneNumbers = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentContactPhoneNumbers->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentContactPhoneNumbers->size()) { + last = currentContactPhoneNumbers->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + contactPhoneNumbers->push_back(currentContactPhoneNumbers->at(i)); + } + + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactPhoneNumberArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactPhoneNumberArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberArrayPtr currentContactPhoneNumbers = priv->getObject(); + std::sort(currentContactPhoneNumbers->begin(), currentContactPhoneNumbers->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactPhoneNumberArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactPhoneNumberArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSContactPhoneNumberArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactPhoneNumberArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactPhoneNumberArray.h b/src/standards/Tizen/Contact/JSContactPhoneNumberArray.h new file mode 100755 index 0000000..506647d --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactPhoneNumberArray.h @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactPhoneNumberArray.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_PHONE_NUMBER_ARRAY_H_ +#define _TIZEN_CONTACT_JS_CONTACT_PHONE_NUMBER_ARRAY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSContactPhoneNumberArrayPriv; + +class JSContactPhoneNumberArray +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const TizenApis::Api::Contact::ContactPhoneNumberArrayPtr &contactPhoneNumbers); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactPhoneNumberArrayPtr getContactPhoneNumberArray(JSContextRef context, JSValueRef value); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_PHONE_NUMBER_ARRAY_H_ diff --git a/src/standards/Tizen/Contact/JSContactPhoneNumberTypeArray.cpp b/src/standards/Tizen/Contact/JSContactPhoneNumberTypeArray.cpp new file mode 100755 index 0000000..7d6b1c6 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactPhoneNumberTypeArray.cpp @@ -0,0 +1,585 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactPhoneNumberTypeArray.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactPhoneNumberTypeArray.h" + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassDefinition JSContactPhoneNumberTypeArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSContactPhoneNumberTypeArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactPhoneNumberTypeArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSContactPhoneNumberTypeArray::m_jsClassRef = JSClassCreate( + JSContactPhoneNumberTypeArray::getClassInfo()); + +JSValueRef JSContactPhoneNumberTypeArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + JSContactPhoneNumberTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactPhoneNumberTypeArrayPtr typeArray = priv->getObject(); + if (typeArray) { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + return converter->toJSValueRef(typeArray->size()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSContactPhoneNumberTypeArray::createArray(JSContextRef context, + const ContactPhoneNumberTypeArrayPtr &typeArray) +{ + JSContactPhoneNumberTypeArrayPriv *priv = new JSContactPhoneNumberTypeArrayPriv(context, typeArray); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSContactPhoneNumberTypeArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSContactPhoneNumberTypeArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +bool JSContactPhoneNumberTypeArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactPhoneNumberTypeArrayPtr JSContactPhoneNumberTypeArray::getContactPhoneNumberTypeArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactPhoneNumberTypeArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSContactPhoneNumberTypeArray::initialize(JSContextRef context, + JSObjectRef object) +{ + //LogDebug("enter"); +} + +void JSContactPhoneNumberTypeArray::finalize(JSObjectRef object) +{ + //LogDebug("enter"); + JSContactPhoneNumberTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSContactPhoneNumberTypeArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + //LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactPhoneNumberTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactPhoneNumberTypeArrayPtr typeArray = priv->getObject(); + if (index < typeArray->size()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSContactPhoneNumberTypeArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactPhoneNumberTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactPhoneNumberTypeArrayPtr typeArray = priv->getObject(); + if (index < typeArray->size()) { + std::string result = converter->toContactPhoneNumberTypeStr(typeArray->at(index)); + if (!result.empty()) { + return converter->toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactPhoneNumberTypeArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + std::string str; + if (!JSValueIsUndefined(context, value)) { + str = converter->toString(value); + } + JSContactPhoneNumberTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactPhoneNumberTypeArrayPtr typeArray = priv->getObject(); + if (!typeArray) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (typeArray->size() <= index) { + typeArray->resize(index + 1); + } + (*typeArray)[index] = converter->toContactPhoneNumberType(str); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + } + return false; +} + +JSValueRef JSContactPhoneNumberTypeArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + ContactPhoneNumberTypeArrayPtr typeArray = ContactPhoneNumberTypeArrayPtr(new ContactPhoneNumberTypeArray()); + JSContactPhoneNumberTypeArrayPriv *newPrivateObject = new JSContactPhoneNumberTypeArrayPriv( + context, + typeArray); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current typeArray + JSContactPhoneNumberTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberTypeArrayPtr currentStrings = priv->getObject(); + for (size_t i = 0; i < currentStrings->size(); ++i) { + typeArray->push_back(currentStrings->at(i)); + } + + //copy submitted arrays + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + typeArray->push_back(converter->toContactPhoneNumberType(att)); + } + } + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactPhoneNumberTypeArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + JSContactPhoneNumberTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberTypeArrayPtr currentStrings = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentStrings->size(); ++i) { + if (i != 0) { + result += separator; + } + result += currentStrings->at(i); + } + return converter->toJSValueRef(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactPhoneNumberTypeArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactPhoneNumberTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberTypeArrayPtr currentStrings = priv->getObject(); + if (currentStrings->size() > 0) { + std::string result = + converter->toContactPhoneNumberTypeStr(currentStrings->at(currentStrings->size() - 1)); + currentStrings->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactPhoneNumberTypeArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactPhoneNumberTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberTypeArrayPtr currentStrings = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentStrings->push_back(converter->toContactPhoneNumberType(arguments[i])); + } + return converter->toJSValueRef(currentStrings->size()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactPhoneNumberTypeArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + JSContactPhoneNumberTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberTypeArrayPtr currentStrings = priv->getObject(); + std::reverse(currentStrings->begin(), currentStrings->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactPhoneNumberTypeArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + JSContactPhoneNumberTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberTypeArrayPtr currentStrings = priv->getObject(); + if (currentStrings->size() > 0) { + std::string result = converter->toContactPhoneNumberTypeStr(currentStrings->at(0)); + currentStrings->erase(currentStrings->begin()); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactPhoneNumberTypeArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + ContactConverterFactory::ConverterType converter = ContactConverterFactory::getConverter(context); + ContactPhoneNumberTypeArrayPtr typeArray = ContactPhoneNumberTypeArrayPtr(new ContactPhoneNumberTypeArray()); + JSContactPhoneNumberTypeArrayPriv *newPrivateObject = new JSContactPhoneNumberTypeArrayPriv( + context, + typeArray); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current typeArray + JSContactPhoneNumberTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberTypeArrayPtr currentStrings = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentStrings->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentStrings->size()) { + last = currentStrings->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + typeArray->push_back(currentStrings->at(i)); + } + + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactPhoneNumberTypeArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + JSContactPhoneNumberTypeArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactPhoneNumberTypeArrayPtr currentStrings = priv->getObject(); + std::sort(currentStrings->begin(), currentStrings->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactPhoneNumberTypeArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactPhoneNumberTypeArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSContactPhoneNumberTypeArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactPhoneNumberTypeArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactPhoneNumberTypeArray.h b/src/standards/Tizen/Contact/JSContactPhoneNumberTypeArray.h new file mode 100755 index 0000000..d45525b --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactPhoneNumberTypeArray.h @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactPhoneNumberTypeArray.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_PHONE_NUMBER_TYPE_ARRAY_H_ +#define _TIZEN_CONTACT_JS_CONTACT_PHONE_NUMBER_TYPE_ARRAY_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSContactPhoneNumberTypeArrayPriv; + +class JSContactPhoneNumberTypeArray +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const TizenApis::Api::Contact::ContactPhoneNumberTypeArrayPtr &Strings); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactPhoneNumberTypeArrayPtr getContactPhoneNumberTypeArray(JSContextRef context, JSValueRef value); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_PHONE_NUMBER_TYPE_ARRAY_H_ diff --git a/src/standards/Tizen/Contact/JSContactProperties.cpp b/src/standards/Tizen/Contact/JSContactProperties.cpp new file mode 100755 index 0000000..dad006d --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactProperties.cpp @@ -0,0 +1,799 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactProperties.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSContactProperties class + */ + +#include +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactProperties.h" + +#define CONTACT_CLASS_NAME "ContactProperties" +#define CONTACT_PROP_ATTR_NAME "name" +#define CONTACT_PROP_ATTR_ACCOUNT "account" +#define CONTACT_PROP_ATTR_ADDRESSES "addresses" +#define CONTACT_PROP_ATTR_PHOTO_URI "photoURI" +#define CONTACT_PROP_ATTR_PHONE_NUMBERS "phoneNumbers" +#define CONTACT_PROP_ATTR_EMAILS "emails" +#define CONTACT_PROP_ATTR_BIRTHDAY "birthday" +#define CONTACT_PROP_ATTR_ANNIVERSARIES "anniversaries" +#define CONTACT_PROP_ATTR_ORGANIZATION "organization" +#define CONTACT_PROP_ATTR_NOTES "notes" +#define CONTACT_PROP_ATTR_URLS "urls" +#define CONTACT_PROP_ATTR_LAST_UPDATED "lastUpdated" +#define CONTACT_PROP_ATTR_IS_FAVORITE "isFavorite" +#define CONTACT_PROP_ATTR_RINGTONE_URI "ringtoneURI" +#define CONTACT_PROP_ATTR_CATEGORIES "categories" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassRef JSContactProperties::m_classRef = NULL; + +JSClassDefinition JSContactProperties::m_classInfo = +{ + 0, + kJSClassAttributeNone, + CONTACT_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticValue JSContactProperties::m_property[] = { + { CONTACT_PROP_ATTR_NAME, getName, setName, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_ACCOUNT, getAccount, setAccount, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_ADDRESSES, getAddresses, setAddresses, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_PHOTO_URI, getPhotoURI, setPhotoURI, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_PHONE_NUMBERS, getPhoneNumbers, setPhoneNumbers, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_EMAILS, getEmails, setEmails, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_BIRTHDAY, getBirthday, setBirthday, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_ANNIVERSARIES, getAnniversaries, setAnniversaries, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_ORGANIZATION, getOrganization, setOrganization, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_NOTES, getNotes, setNotes, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_URLS, getUrls, setUrls, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_IS_FAVORITE, getIsFavorite, setIsFavorite, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_RINGTONE_URI, getRingtoneURI, setRingtoneURI, kJSPropertyAttributeNone }, + { CONTACT_PROP_ATTR_CATEGORIES, getCategories, setCategories, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactProperties::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSContactProperties::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSContactProperties::createJSObject(JSContextRef context +// FIXME + ) +{ + ContactPropertiesPtr privateData = ContactPropertiesPtr(new ContactProperties()); + JSContactPropertiesPriv *priv = new JSContactPropertiesPriv(context, privateData); + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast(priv)); + if (NULL == jsValueRef) + { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +bool JSContactProperties::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactPropertiesPtr JSContactProperties::getContactProperties(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + JSContactPropertiesPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + + return priv->getObject(); +} + +void JSContactProperties::Initialize(JSContextRef context, JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSContactProperties::Finalize(JSObjectRef object) +{ + //delete (JSObjectGetPrivate(object)); +} + +ContactPropertiesPtr JSContactProperties::getPrivData(JSObjectRef object) +{ + //LogDebug("entered"); + JSContactPropertiesPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + + ContactPropertiesPtr result = priv->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + + return result; +} + +JSValueRef JSContactProperties::getName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getName()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setName(converter->toContactName(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactProperties::getAccount(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getAccount()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setAccount(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setAccount(converter->toContactAccount(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactProperties::getAddresses(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getAddresses()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setAddresses(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setAddresses( + converter->toContactAddressArray(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactProperties::getPhotoURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getPhotoURI()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setPhotoURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setPhotoURI(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactProperties::getPhoneNumbers(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getPhoneNumbers()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setPhoneNumbers(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setPhoneNumbers( + converter->toContactPhoneNumberArray(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactProperties::getEmails(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getEmails()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setEmails(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setEmails(converter->toContactEmailAddressArray(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactProperties::getBirthday(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + if(contactProperties->getBirthdayIsSet()) + return converter->toJSValueRef(contactProperties->getBirthday()); + else + return JSValueMakeNull(context); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setBirthday(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setBirthday(converter->toDateTm(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactProperties::getAnniversaries(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getAnniversaries()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setAnniversaries(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setAnniversaries( + converter->toContactAnniversaryArray(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactProperties::getOrganization(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getOrganization()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setOrganization(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setOrganization(converter->toContactOrganization(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactProperties::getNotes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getNotes()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setNotes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setNotes(converter->toStringArray(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactProperties::getUrls(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getUrls()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setUrls(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setUrls(converter->toContactWebSiteArray(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactProperties::getIsFavorite(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getIsFavorite()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setIsFavorite(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setIsFavorite(converter->toBool(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactProperties::getRingtoneURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getRingtoneURI()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setRingtoneURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setRingtoneURI(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +JSValueRef JSContactProperties::getCategories(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactPropertiesPtr contactProperties = getPrivData(object); + return converter->toJSValueRef(contactProperties->getCategories()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSContactProperties::setCategories(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactPropertiesPtr contactProperties = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + contactProperties->setCategories(converter->toStringArray(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactProperties.h b/src/standards/Tizen/Contact/JSContactProperties.h new file mode 100755 index 0000000..d8ccbdf --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactProperties.h @@ -0,0 +1,242 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactProperties.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSContactProperties class + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_PROPERTIES_H_ +#define _TIZEN_CONTACT_JS_CONTACT_PROPERTIES_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject JSContactPropertiesPriv; + +class JSContactProperties { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactPropertiesPtr getContactProperties(JSContextRef context, JSValueRef value); + +private: + /** + * The callback invoked when an object is first created. + */ + static void Initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void Finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static TizenApis::Api::Contact::ContactPropertiesPtr getPrivData(JSObjectRef object); + + static JSValueRef getName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getAccount(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setAccount(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getAddresses(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setAddresses(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getPhotoURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setPhotoURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getPhoneNumbers(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setPhoneNumbers(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getEmails(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setEmails(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getBirthday(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setBirthday(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getAnniversaries(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setAnniversaries(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getOrganization(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setOrganization(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getNotes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setNotes(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getUrls(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setUrls(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getIsFavorite(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setIsFavorite(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getRingtoneURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setRingtoneURI(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getCategories(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setCategories(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_PROPERTIES_H_ diff --git a/src/standards/Tizen/Contact/JSContactWebSite.cpp b/src/standards/Tizen/Contact/JSContactWebSite.cpp new file mode 100755 index 0000000..e8530d5 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactWebSite.cpp @@ -0,0 +1,237 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactWebSite.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSContactWebSite class + */ + +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactWebSite.h" + +#define CONTACT_CLASS_NAME "ContactWebSite" + +#define CONTACT_ATTR_URL "url" +#define CONTACT_ATTR_TYPE "type" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassRef JSContactWebSite::m_classRef = NULL; + +JSClassDefinition JSContactWebSite::m_classInfo = +{ + 0, + kJSClassAttributeNone, + CONTACT_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticValue JSContactWebSite::m_property[] = { + { CONTACT_ATTR_URL, getUrl, setUrl, kJSPropertyAttributeNone }, + { CONTACT_ATTR_TYPE, getType, setType, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactWebSite::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSContactWebSite::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSContactWebSite::createJSObject(JSContextRef context, + const std::string url, + const ContactWebSiteType type) +{ + ContactWebSitePtr privateData = ContactWebSitePtr(new ContactWebSite()); + if(url != "") + { + privateData->setUrl(url); + privateData->setType(type); + } + JSContactWebSitePriv *priv = new JSContactWebSitePriv(context, privateData); + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast(priv)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +bool JSContactWebSite::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactWebSitePtr JSContactWebSite::getContactWebSite(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactWebSitePriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSContactWebSite::Initialize(JSContextRef context, JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSContactWebSite::Finalize(JSObjectRef object) +{ + //delete (JSObjectGetPrivate(object)); +} + +ContactWebSitePtr JSContactWebSite::getPrivData(JSObjectRef object) +{ + //LogDebug("entered"); + JSContactWebSitePriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + ContactWebSitePtr result = priv->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + return result; +} + +JSValueRef JSContactWebSite::getUrl(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactWebSitePtr webSite = getPrivData(object); + return converter->toJSValueRef(webSite->getUrl()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactWebSite::setUrl(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactWebSitePtr webSite = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + webSite->setUrl(converter->toString(value)); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + + +JSValueRef JSContactWebSite::getType(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactWebSitePtr webSite = getPrivData(object); + std::string ret = converter->toContactWebSiteTypeStr(webSite->getType()); + return converter->toJSValueRef(ret); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactWebSite::setType(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ContactWebSitePtr webSite = getPrivData(object); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactWebSiteType type = converter->toContactWebSiteType(converter->toString(value)); + webSite->setType(type); + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + } + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + return false; +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactWebSite.h b/src/standards/Tizen/Contact/JSContactWebSite.h new file mode 100755 index 0000000..d53d641 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactWebSite.h @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactWebSite.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSContactWebSite class + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_WEB_SITE_H_ +#define _TIZEN_CONTACT_JS_CONTACT_WEB_SITE_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject< TizenApis::Api::Contact::ContactWebSitePtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSContactWebSitePriv; + +class JSContactWebSite { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context, + const std::string url = "", + const TizenApis::Api::Contact::ContactWebSiteType type = TizenApis::Api::Contact::WEBSITE_TYPE_HOMEPAGE); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactWebSitePtr getContactWebSite(JSContextRef context, JSValueRef value); + +private: + /** + * The callback invoked when an object is first created. + */ + static void Initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void Finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static TizenApis::Api::Contact::ContactWebSitePtr getPrivData(JSObjectRef object); + + static JSValueRef getUrl(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setUrl(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getType(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setType(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_WEB_SITE_H_ diff --git a/src/standards/Tizen/Contact/JSContactWebSiteArray.cpp b/src/standards/Tizen/Contact/JSContactWebSiteArray.cpp new file mode 100755 index 0000000..9c2b5f6 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactWebSiteArray.cpp @@ -0,0 +1,589 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactWebSiteArray.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSContactWebSiteArray.h" + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Contact; + +JSClassDefinition JSContactWebSiteArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSContactWebSiteArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSContactWebSiteArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSContactWebSiteArray::m_jsClassRef = JSClassCreate( + JSContactWebSiteArray::getClassInfo()); + +JSValueRef JSContactWebSiteArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + JSContactWebSiteArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactWebSiteArrayPtr webSites = priv->getObject(); + if (webSites) { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + return converter->toJSValueRef(webSites->size()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactWebSiteArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ContactWebSiteArrayPtr JSContactWebSiteArray::getContactWebSiteArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSContactWebSiteArrayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +JSObjectRef JSContactWebSiteArray::createArray(JSContextRef context, + const ContactWebSiteArrayPtr &webSites) +{ + JSContactWebSiteArrayPriv *priv = new JSContactWebSiteArrayPriv(context, webSites); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSContactWebSiteArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSContactWebSiteArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +void JSContactWebSiteArray::initialize(JSContextRef context, + JSObjectRef object) +{ + //LogDebug("enter"); +} + +void JSContactWebSiteArray::finalize(JSObjectRef object) +{ + //LogDebug("enter"); + JSContactWebSiteArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSContactWebSiteArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactWebSiteArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactWebSiteArrayPtr webSites = priv->getObject(); + if (index < webSites->size()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSContactWebSiteArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSContactWebSiteArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactWebSiteArrayPtr webSites = priv->getObject(); + if (index < webSites->size()) { + ContactWebSitePtr result = webSites->at(index); + if (result) { + return converter->toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSContactWebSiteArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + //LogDebug("enter"); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + ContactWebSitePtr webSite; + if (!JSValueIsUndefined(context, value)) { + webSite = converter->toContactWebSite(value); + } + JSContactWebSiteArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + ContactWebSiteArrayPtr webSites = priv->getObject(); + if (!webSites) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (webSites->size() <= index) { + webSites->resize(index + 1); + } + (*webSites)[index] = webSite; + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + } + return false; +} + +JSValueRef JSContactWebSiteArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + ContactWebSiteArrayPtr webSites = ContactWebSiteArrayPtr(new ContactWebSiteArray()); + JSContactWebSiteArrayPriv *newPrivateObject = new JSContactWebSiteArrayPriv(context, webSites); + JSValueRef result = JSObjectMake(context, getClassRef(), newPrivateObject); + + //copy current webSites + JSContactWebSiteArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactWebSiteArrayPtr currentWebSites = priv->getObject(); + for (size_t i = 0; i < currentWebSites->size(); ++i) { + webSites->push_back(currentWebSites->at(i)); + } + + //copy submitted arrays + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + webSites->push_back(converter->toContactWebSite(att)); + } + } + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactWebSiteArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactWebSiteArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactWebSiteArrayPtr currentWebSites = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentWebSites->size(); ++i) { + if (i != 0) { + result += separator; + } + //FIXME : to be changed to support join + //result += currentWebSites->at(i); + } + return converter->toJSValueRef(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactWebSiteArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactWebSiteArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactWebSiteArrayPtr currentWebSites = priv->getObject(); + if (currentWebSites->size() > 0) { + ContactWebSitePtr result = currentWebSites->at( + currentWebSites->size() - 1); + currentWebSites->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactWebSiteArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactWebSiteArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactWebSiteArrayPtr currentWebSites = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentWebSites->push_back(converter->toContactWebSite(arguments[i])); + } + return converter->toJSValueRef(currentWebSites->size()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactWebSiteArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactWebSiteArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactWebSiteArrayPtr currentWebSites = priv->getObject(); + std::reverse(currentWebSites->begin(), currentWebSites->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactWebSiteArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactWebSiteArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactWebSiteArrayPtr currentWebSites = priv->getObject(); + if (currentWebSites->size() > 0) { + ContactWebSitePtr result = currentWebSites->at(0); + currentWebSites->erase(currentWebSites->begin()); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactWebSiteArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + ContactWebSiteArrayPtr webSites = ContactWebSiteArrayPtr(new ContactWebSiteArray()); + JSContactWebSiteArrayPriv *newPrivateObject = new JSContactWebSiteArrayPriv( + context, + webSites); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current webSites + JSContactWebSiteArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactWebSiteArrayPtr currentWebSites = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentWebSites->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentWebSites->size()) { + last = currentWebSites->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + webSites->push_back(currentWebSites->at(i)); + } + + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSContactWebSiteArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + ContactConverterFactory::ConverterType converter = + ContactConverterFactory::getConverter(context); + JSContactWebSiteArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + ContactWebSiteArrayPtr currentWebSites = priv->getObject(); + std::sort(currentWebSites->begin(), currentWebSites->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactWebSiteArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactWebSiteArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSContactWebSiteArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSContactWebSiteArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSContactWebSiteArray.h b/src/standards/Tizen/Contact/JSContactWebSiteArray.h new file mode 100755 index 0000000..28c1915 --- /dev/null +++ b/src/standards/Tizen/Contact/JSContactWebSiteArray.h @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSContactWebSiteArray.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_CONTACT_WEB_SITE_ARRAY_H_ +#define _TIZEN_CONTACT_JS_CONTACT_WEB_SITE_ARRAY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT< TizenApis::Api::Contact::ContactWebSiteArrayPtr >::Type JSContactWebSiteArrayPriv; + +class JSContactWebSiteArray +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const TizenApis::Api::Contact::ContactWebSiteArrayPtr &webSites); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static TizenApis::Api::Contact::ContactWebSiteArrayPtr getContactWebSiteArray(JSContextRef context, JSValueRef value); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_CONTACT_WEB_SITE_ARRAY_H_ diff --git a/src/standards/Tizen/Contact/JSStringArray.cpp b/src/standards/Tizen/Contact/JSStringArray.cpp new file mode 100755 index 0000000..5e97009 --- /dev/null +++ b/src/standards/Tizen/Contact/JSStringArray.cpp @@ -0,0 +1,591 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSStringArray.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include +#include "ContactConverter.h" +#include "JSStringArray.h" + +#define FUNCTION_CONCAT "concat" +#define FUNCTION_JOIN "join" +#define FUNCTION_POP "pop" +#define FUNCTION_PUSH "push" +#define FUNCTION_REVERSE "reverse" +#define FUNCTION_SHIFT "shift" +#define FUNCTION_SLICE "slice" +#define FUNCTION_SORT "sort" +#define FUNCTION_SPLICE "splice" +#define FUNCTION_TOSTRING "toString" +#define FUNCTION_UNSHIFT "unshift" +#define FUNCTION_VALUEOF "valueOf" +#define ARRAY "Array" +#define ATTRIBUTE_LENGTH "length" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +using namespace TizenApis::Commons; + +JSClassDefinition JSStringArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSStringArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSStringArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSStringArray::m_jsClassRef = JSClassCreate( + JSStringArray::getClassInfo()); + +JSValueRef JSStringArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + JSStringArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + StringArrayPtr strs = priv->getObject(); + if (strs) { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + return converter->toJSValueRef(strs->size()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSObjectRef JSStringArray::createArray(JSContextRef context, + const StringArrayPtr &strs) +{ + JSStringArrayPriv *priv = new JSStringArrayPriv(context, strs); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSStringArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSStringArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +bool JSStringArray::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +StringArrayPtr JSStringArray::getStringArray(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSStringArrayPriv* priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +void JSStringArray::initialize(JSContextRef context, + JSObjectRef object) +{ + //LogDebug("enter"); +} + +void JSStringArray::finalize(JSObjectRef object) +{ + //LogDebug("enter"); + JSStringArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSStringArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + //LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSStringArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + StringArrayPtr strs = priv->getObject(); + if (index < strs->size()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSStringArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + //LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + JSStringArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + StringArrayPtr strs = priv->getObject(); + if (index < strs->size()) { + std::string result = strs->at(index); + if (!result.empty()) { + return converter->toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSStringArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + //LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + Try + { + size_t index = converter->toSizeT(propertyName); + std::string str; + if (!JSValueIsUndefined(context, value)) { + str = converter->toString(value); + } + JSStringArrayPriv* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + StringArrayPtr strs = priv->getObject(); + if (!strs) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + if (strs->size() <= index) { + strs->resize(index + 1); + } + (*strs)[index] = str; + return true; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); + } + return false; +} + +JSValueRef JSStringArray::concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + StringArrayPtr strs = StringArrayPtr(new StringArray()); + JSStringArrayPriv *newPrivateObject = new JSStringArrayPriv( + context, + strs); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current strs + JSStringArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + StringArrayPtr currentStrings = priv->getObject(); + for (size_t i = 0; i < currentStrings->size(); ++i) { + strs->push_back(currentStrings->at(i)); + } + + //copy submitted arrays + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + for (size_t i = 0; i < argumentCount; ++i) { + if (!JSIsArrayValue(context, arguments[i])) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + // process array of strings + JSObjectRef arrayObj = converter->toJSObjectRef(arguments[i]); + unsigned int len = JSGetArrayLength(context, arrayObj); + for (unsigned int e = 0; e < len; ++e) { + JSValueRef att = JSGetArrayElement(context, arrayObj, e); + strs->push_back(converter->toString(att)); + } + } + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSStringArray::join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + std::string result; + std::string separator(","); + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSStringArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + StringArrayPtr currentStrings = priv->getObject(); + if (argumentCount > 0 && JSValueIsString(context, arguments[0])) { + separator = converter->toString(arguments[0]); + } + for (size_t i = 0; i < currentStrings->size(); ++i) { + if (i != 0) { + result += separator; + } + result += currentStrings->at(i); + } + return converter->toJSValueRef(result); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSStringArray::pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSStringArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + StringArrayPtr currentStrings = priv->getObject(); + if (currentStrings->size() > 0) { + std::string result = currentStrings->at( + currentStrings->size() - 1); + currentStrings->pop_back(); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSStringArray::push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSStringArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + StringArrayPtr currentStrings = priv->getObject(); + for (size_t i = 0; i < argumentCount; ++i) { + currentStrings->push_back(converter->toString(arguments[i])); + } + return converter->toJSValueRef(currentStrings->size()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSStringArray::reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSStringArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + StringArrayPtr currentStrings = priv->getObject(); + std::reverse(currentStrings->begin(), currentStrings->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSStringArray::shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSStringArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + StringArrayPtr currentStrings = priv->getObject(); + if (currentStrings->size() > 0) { + std::string result = currentStrings->at(0); + currentStrings->erase(currentStrings->begin()); + return converter->toJSValueRef(result); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSStringArray::slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("enter"); + Try + { + if (argumentCount < 1) { + return JSValueMakeUndefined(context); + } + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + StringArrayPtr strs = StringArrayPtr(new StringArray()); + JSStringArrayPriv *newPrivateObject = new JSStringArrayPriv( + context, + strs); + JSValueRef result = JSObjectMake(context, + getClassRef(), newPrivateObject); + + //copy current strs + JSStringArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + StringArrayPtr currentStrings = priv->getObject(); + std::size_t first = converter->toSizeT(arguments[0]); + std::size_t last = currentStrings->size() - 1; + if (argumentCount > 1) { + last = converter->toSizeT(arguments[1]); + if (last >= currentStrings->size()) { + last = currentStrings->size() - 1; + } + } + if (first < 0) { + first = 0; + } + for (size_t i = first; i <= last; ++i) { + strs->push_back(currentStrings->at(i)); + } + + return result; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type mismatch"); +} + +JSValueRef JSStringArray::sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::BasicConverter converter = + WrtDeviceApis::CommonsJavaScript::BasicConverterFactory::getConverter(context); + JSStringArrayPriv* priv = + static_cast(JSObjectGetPrivate(thisObject)); + StringArrayPtr currentStrings = priv->getObject(); + std::sort(currentStrings->begin(), currentStrings->end()); + return thisObject; + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSStringArray::splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSStringArray::toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return join(context, function, thisObject, 0, arguments, exception); +} + +JSValueRef JSStringArray::unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSStringArray::valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +} // Contact +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Contact/JSStringArray.h b/src/standards/Tizen/Contact/JSStringArray.h new file mode 100755 index 0000000..4818e82 --- /dev/null +++ b/src/standards/Tizen/Contact/JSStringArray.h @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSStringArray.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_CONTACT_JS_STRING_ARRAY_H_ +#define _TIZEN_CONTACT_JS_STRING_ARRAY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +typedef std::vector StringArray; +typedef DPL::SharedPtr StringArrayPtr; +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSStringArrayPriv; + +class JSStringArray +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const StringArrayPtr &Strings); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static StringArrayPtr getStringArray(JSContextRef context, JSValueRef value); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; + +} // Contact +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_CONTACT_JS_STRING_ARRAY_H_ diff --git a/src/standards/Tizen/Contact/config.xml b/src/standards/Tizen/Contact/config.xml new file mode 100755 index 0000000..13f839f --- /dev/null +++ b/src/standards/Tizen/Contact/config.xml @@ -0,0 +1,26 @@ + + + + libwrt-plugins-tizen-1.0-contact.so + contact.install.uri + SAMSUNG plugin group + SAMSUNG certificate authority + AAAABBBBCCCCDDDEEEE0000 + + + http://tizen.org/api/contact + contact.read + contact.write + + + + http://tizen.org/api/contact.read + contact.read + + + + http://tizen.org/api/contact.write + contact.read + contact.write + + diff --git a/src/standards/Tizen/Contact/plugin_config.cpp b/src/standards/Tizen/Contact/plugin_config.cpp new file mode 100755 index 0000000..adff30c --- /dev/null +++ b/src/standards/Tizen/Contact/plugin_config.cpp @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include + +#include "plugin_config.h" + +#define CONTACT_FEATURE_API "http://tizen.org/api/contact" +#define CONTACT_FEATURE_API_READ "http://tizen.org/api/contact.read" +#define CONTACT_FEATURE_API_WRITE "http://tizen.org/api/contact.write" + +#define CONTACT_DEVICE_CAP_READ "contact.read" +#define CONTACT_DEVICE_CAP_WRITE "contact.write" + +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +static FunctionMapping createContactFunctions(); + +static FunctionMapping ContactFunctions = + createContactFunctions(); + +DEFINE_FUNCTION_GETTER(Contact, ContactFunctions); + +static FunctionMapping createContactFunctions() +{ + /** + * Device capabilities + */ + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_CONTACT_READ, CONTACT_DEVICE_CAP_READ); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_CONTACT_WRITE, CONTACT_DEVICE_CAP_WRITE); + + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_CONTACT_READ); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_CONTACT_READ, DEVICE_CAP_CONTACT_READ); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_CONTACT_WRITE); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_CONTACT_WRITE, DEVICE_CAP_CONTACT_WRITE); + + /** + * Api Features + */ + ACE_CREATE_FEATURE(FEATURE_CONTACT, CONTACT_FEATURE_API); + ACE_CREATE_FEATURE(FEATURE_CONTACT_READ, CONTACT_FEATURE_API_READ); + ACE_CREATE_FEATURE(FEATURE_CONTACT_WRITE, CONTACT_FEATURE_API_WRITE); + + ACE_CREATE_FEATURE_LIST(CONTACT_FEATURES_CONTACT_READ_WRITE); + ACE_ADD_API_FEATURE(CONTACT_FEATURES_CONTACT_READ_WRITE, + FEATURE_CONTACT); + ACE_ADD_API_FEATURE(CONTACT_FEATURES_CONTACT_READ_WRITE, + FEATURE_CONTACT_READ); + ACE_ADD_API_FEATURE(CONTACT_FEATURES_CONTACT_READ_WRITE, + FEATURE_CONTACT_WRITE); + + ACE_CREATE_FEATURE_LIST(CONTACT_FEATURES_CONTACT_READ); + ACE_ADD_API_FEATURE(CONTACT_FEATURES_CONTACT_READ, FEATURE_CONTACT); + ACE_ADD_API_FEATURE(CONTACT_FEATURES_CONTACT_READ, FEATURE_CONTACT_READ); + + ACE_CREATE_FEATURE_LIST(CONTACT_FEATURES_CONTACT_WRITE); + ACE_ADD_API_FEATURE(CONTACT_FEATURES_CONTACT_WRITE, FEATURE_CONTACT); + ACE_ADD_API_FEATURE(CONTACT_FEATURES_CONTACT_WRITE, + FEATURE_CONTACT_WRITE); + + ACE_CREATE_FEATURE_LIST(CONTACT_FEATURES_CONTACT); + ACE_ADD_API_FEATURE(CONTACT_FEATURES_CONTACT, + FEATURE_CONTACT); + + ACE_CREATE_FEATURE_LIST(CONTACT_FEATURES_READ); + ACE_ADD_API_FEATURE(CONTACT_FEATURES_CONTACT_READ, + FEATURE_CONTACT_READ); + + ACE_CREATE_FEATURE_LIST(CONTACT_FEATURES_WRITE); + ACE_ADD_API_FEATURE(CONTACT_FEATURES_WRITE, + FEATURE_CONTACT_WRITE); + + /** + * Functions + */ + + FunctionMapping contactMapping; + + //getAddressBooks + AceFunction getAddressBooksFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_CONTACTS, + CONTACT_FUNCTION_API_GET_ADDRESS_BOOKS, + CONTACT_FEATURES_CONTACT_READ_WRITE, + DEVICE_LIST_CONTACT_READ); + + contactMapping.insert(std::make_pair( + CONTACT_FUNCTION_API_GET_ADDRESS_BOOKS, + getAddressBooksFunc)); + + //getDefaultAddressBook + AceFunction getDefaultAddressBookFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_DEFAULT_CONTACT, + CONTACT_FUNCTION_API_GET_DEFAULT_ADDRESS_BOOK, + CONTACT_FEATURES_CONTACT_READ_WRITE, + DEVICE_LIST_CONTACT_READ); + + contactMapping.insert(std::make_pair( + CONTACT_FUNCTION_API_GET_DEFAULT_ADDRESS_BOOK, + getDefaultAddressBookFunc)); + + + //convertFromString + AceFunction convertFromStringFunc = ACE_CREATE_FUNCTION( + FUNCTION_CREATE_EVENT_FROM_STRING, + CONTACT_FUNCTION_API_CONVERT_FROM_STRING, + CONTACT_FEATURES_CONTACT_READ_WRITE, + DEVICE_LIST_CONTACT_READ); + + contactMapping.insert(std::make_pair( + CONTACT_FUNCTION_API_CONVERT_FROM_STRING, + convertFromStringFunc)); + + //convertToString + AceFunction convertToStringFunc = ACE_CREATE_FUNCTION( + FUNCTION_EXPORT_EVENT_TO_STRING, + CONTACT_FUNCTION_API_CONVERT_TO_STRING, + CONTACT_FEATURES_CONTACT_READ_WRITE, + DEVICE_LIST_CONTACT_READ); + + contactMapping.insert(std::make_pair( + CONTACT_FUNCTION_API_CONVERT_TO_STRING, + convertToStringFunc)); + + //add + AceFunction addFunc = ACE_CREATE_FUNCTION( + FUNCTION_ADD_EVENT, + CONTACT_FUNCTION_API_ADD, + CONTACT_FEATURES_CONTACT_WRITE, + DEVICE_LIST_CONTACT_WRITE); + + contactMapping.insert(std::make_pair( + CONTACT_FUNCTION_API_ADD, + addFunc)); + + //addBatch + AceFunction addBatchFunc = ACE_CREATE_FUNCTION( + FUNCTION_ADD_EVENTS, + CONTACT_FUNCTION_API_ADD_BATCH, + CONTACT_FEATURES_CONTACT_WRITE, + DEVICE_LIST_CONTACT_WRITE); + + contactMapping.insert(std::make_pair( + CONTACT_FUNCTION_API_ADD_BATCH, + addBatchFunc)); + + //update + AceFunction updateFunc = ACE_CREATE_FUNCTION( + FUNCTION_UPDATE_EVENT, + CONTACT_FUNCTION_API_UPDATE, + CONTACT_FEATURES_CONTACT_WRITE, + DEVICE_LIST_CONTACT_WRITE); + + contactMapping.insert(std::make_pair( + CONTACT_FUNCTION_API_UPDATE, + updateFunc)); + + //updateBatch + AceFunction updateBatchFunc = ACE_CREATE_FUNCTION( + FUNCTION_UPDATE_EVENTS, + CONTACT_FUNCTION_API_UPDATE_BATCH, + CONTACT_FEATURES_CONTACT_WRITE, + DEVICE_LIST_CONTACT_WRITE); + + contactMapping.insert(std::make_pair( + CONTACT_FUNCTION_API_UPDATE_BATCH, + updateBatchFunc)); + + //remove + AceFunction removeFunc = ACE_CREATE_FUNCTION( + FUNCTION_DELETE_EVENT, + CONTACT_FUNCTION_API_REMOVE, + CONTACT_FEATURES_CONTACT_WRITE, + DEVICE_LIST_CONTACT_WRITE); + + contactMapping.insert(std::make_pair( + CONTACT_FUNCTION_API_REMOVE, + removeFunc)); + + //removeBatch + AceFunction removeBatchFunc = ACE_CREATE_FUNCTION( + FUNCTION_DELETE_EVENTS, + CONTACT_FUNCTION_API_REMOVE_BATCH, + CONTACT_FEATURES_CONTACT_WRITE, + DEVICE_LIST_CONTACT_WRITE); + + contactMapping.insert(std::make_pair( + CONTACT_FUNCTION_API_REMOVE_BATCH, + removeBatchFunc)); + + //find + AceFunction findFunc = ACE_CREATE_FUNCTION( + FUNCTION_FIND_EVENTS, + CONTACT_FUNCTION_API_FIND, + CONTACT_FEATURES_CONTACT_READ, + DEVICE_LIST_CONTACT_READ); + + contactMapping.insert(std::make_pair( + CONTACT_FUNCTION_API_FIND, + findFunc)); + + //addChangeListener + AceFunction addChangeListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_ADD_CHANGE_LISTENER, + CONTACT_FUNCTION_API_ADD_CHANGE_LISTENER, + CONTACT_FEATURES_CONTACT_READ, + DEVICE_LIST_CONTACT_READ); + + contactMapping.insert(std::make_pair( + CONTACT_FUNCTION_API_ADD_CHANGE_LISTENER, + addChangeListenerFunc)); + + //removeChangeListener + AceFunction removeChangeListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_REMOVE_CHANGE_LISTENER, + CONTACT_FUNCTION_API_REMOVE_CHANGE_LISTENER, + CONTACT_FEATURES_CONTACT_READ, + DEVICE_LIST_CONTACT_READ); + + contactMapping.insert(std::make_pair( + CONTACT_FUNCTION_API_REMOVE_CHANGE_LISTENER, + removeChangeListenerFunc)); + + return contactMapping; +} + +} +} +} diff --git a/src/standards/Tizen/Contact/plugin_config.h b/src/standards/Tizen/Contact/plugin_config.h new file mode 100755 index 0000000..5a6c94b --- /dev/null +++ b/src/standards/Tizen/Contact/plugin_config.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _CONTACT_PLUGIN_CONFIG_H_ +#define _CONTACT_PLUGIN_CONFIG_H_ + +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Contact { + +#define CONTACT_FUNCTION_API_GET_ADDRESS_BOOKS "getAddressBooks" +#define CONTACT_FUNCTION_API_GET_DEFAULT_ADDRESS_BOOK "getDefaultAddressBook" +#define CONTACT_FUNCTION_API_CONVERT_FROM_STRING "convertFromString" +#define CONTACT_FUNCTION_API_CONVERT_TO_STRING "convertToString" +#define CONTACT_FUNCTION_API_ADD "add" +#define CONTACT_FUNCTION_API_ADD_BATCH "addBatch" +#define CONTACT_FUNCTION_API_UPDATE "update" +#define CONTACT_FUNCTION_API_UPDATE_BATCH "updateBatch" +#define CONTACT_FUNCTION_API_REMOVE "remove" +#define CONTACT_FUNCTION_API_REMOVE_BATCH "removeBatch" +#define CONTACT_FUNCTION_API_FIND "find" +#define CONTACT_FUNCTION_API_ADD_CHANGE_LISTENER "addChangeListener" +#define CONTACT_FUNCTION_API_REMOVE_CHANGE_LISTENER "removeChangeListener" + +DECLARE_FUNCTION_GETTER(Contact); + +#define CONTACT_CHECK_ACCESS(globalContext, functionName) \ + aceCheckAccess >( \ + globalContext, \ + getContactFunctionData, \ + functionName) + +} // Contact +} // Tizen1_0 +} // Tizen + +#endif // _CONTACT_PLUGIN_CONFIG_H_ diff --git a/src/standards/Tizen/Contact/plugin_initializer.cpp b/src/standards/Tizen/Contact/plugin_initializer.cpp new file mode 100755 index 0000000..41cc2d0 --- /dev/null +++ b/src/standards/Tizen/Contact/plugin_initializer.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file plugin_initializer.cpp + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief + */ + +#include + +#include +#include +#include "JSContactManager.h" + +void on_widget_start_callback(int widgetId, + JavaScriptContext context, + const engine_interface_t *interface) +{ + LogDebug("[Tizen\\contact] on_widget_start_callback (" << widgetId << ")"); + Try + { + WrtDeviceApis::Commons::WrtWrappersMgr::getInstance().registerWrapper( + widgetId, + context, + interface); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("Wrt wrapper registration failed"); + } +} + +void on_widget_stop_callback(int widgetId) +{ + LogDebug("[Tizen\\contact] on_widget_stop_callback (" << widgetId << ")"); + Try + { + WrtDeviceApis::Commons::WrtWrappersMgr::getInstance().removeWrapper(widgetId); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("Wrt wrapper removal failed"); + } +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) + +PLUGIN_CLASS_MAP_BEGIN + PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, + "contact", + TizenApis::Tizen1_0::Contact::JSContactManager::getClassRef(), + NULL) +PLUGIN_CLASS_MAP_END diff --git a/src/standards/Tizen/Geocoder/CMakeLists.txt b/src/standards/Tizen/Geocoder/CMakeLists.txt new file mode 100755 index 0000000..ee5238c --- /dev/null +++ b/src/standards/Tizen/Geocoder/CMakeLists.txt @@ -0,0 +1,26 @@ +set(TARGET_NAME "wrt-plugins-tizen-1.0-geocoder") + +include_directories(${INCLUDES_PLATFORM_IMPLEMENTATION_GEOCODER}) + +set(SRCS + ${SRCS_PLATFORM_API_GEOCODER} + ${SRCS_PLATFORM_IMPLEMENTATION_GEOCODER} + JSGeocoder.cpp + JSAddress.cpp + JSCoordinates.cpp + GeocoderController.cpp + plugin_initializer.cpp + plugin_config.cpp + ../Common/JSTizenException.cpp + ../Common/TizenExceptionData.cpp + ../Common/JSTizenExceptionFactory.cpp +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMON} + ${LIBS_PLATFORM_IMPLEMENTATION_GEOCODER} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION tizen-1.0-geocoder) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION tizen-1.0-geocoder) diff --git a/src/standards/Tizen/Geocoder/GeocoderController.cpp b/src/standards/Tizen/Geocoder/GeocoderController.cpp new file mode 100644 index 0000000..f570a44 --- /dev/null +++ b/src/standards/Tizen/Geocoder/GeocoderController.cpp @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* + * @author Sangtai Kim(sangtai.kim@samsung.com) + * @version 0.1 + * @brief + */ + +#include "GeocoderController.h" +#include "JSAddress.h" +#include "JSCoordinates.h" + +#include +#include + +#include +#include + +using namespace std; +//using namespace TizenApis::Tizen1_0::Platform; +using namespace WrtDeviceApis::Commons; +using namespace TizenApis::Tizen1_0::Api::Geocoder; + +using namespace TizenApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { + +GeocoderController::GeocoderController(const JSCallbackManagerPtr &callbackManager) : + EventAnswerReceiver (ThreadEnum::NULL_THREAD), m_callbackManager(callbackManager) { + LogDebug("<<<"); +} + +GeocoderController::~GeocoderController() { + LogDebug("<<<"); + LogDebug(">>>"); +} + +void GeocoderController::OnAnswerReceived(const EventGeocoderPtr &event) { + LogDebug("<<<"); + + JSContextRef context = m_callbackManager->getContext(); + + if (event->getExceptionCode() == ExceptionCodes::None) { + LogDebug("result success"); + + GeocoderProperties geocoderProperties; + geocoderProperties.latitude = event->getLatitude(); + geocoderProperties.longitude = event->getLongitude(); + + geocoderProperties.strCountry = event->getCountry(); + geocoderProperties.strRegion = event->getRegion(); + geocoderProperties.strCounty = event->getCounty(); + geocoderProperties.strCity = event->getCity(); + geocoderProperties.strStreet = event->getStreet(); + geocoderProperties.strStreetNumber = event->getStreetNumber(); + geocoderProperties.strPremises = event->getPremises(); + geocoderProperties.strAdditionalInformation = event->getAdditionalInformation(); + geocoderProperties.strPostalCode = event->getPostalCode(); + + JSObjectRef jsObj = NULL; + vector propertiesVector; + + if(event->getEventType() == EventGeocoder::GEOCODER_EVENT_GET_POSITION){ + jsObj = JSCoordinates::createJSObject(m_callbackManager->getContext(), geocoderProperties); + }else if(event->getEventType() == EventGeocoder::GEOCODER_EVENT_GET_ADDRESS){ + jsObj = JSAddress::createJSObject(m_callbackManager->getContext(), geocoderProperties); + }else{ + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter"); + m_callbackManager->callOnError(errorObject); + } + + propertiesVector.push_back(jsObj); + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + + JSValueRef geocoderPropertiesArray[2] = {converter.toJSValueRef(propertiesVector), converter.toJSValueRef(propertiesVector.size())}; + m_callbackManager->callOnSuccess(geocoderPropertiesArray, 2); + + LogDebug("after callOnSuccess"); + } else { + LogDebug("Operation failed. Exception code: " << event->getExceptionCode()); + + JSValueRef errorObject = NULL; + + ExceptionCodes::Enumeration exception = event->getExceptionCode(); + switch(exception){ + case ExceptionCodes::InvalidArgumentException: + errorObject = JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, "invalid parameter"); + break; + case ExceptionCodes::PlatformException: + errorObject = JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::IO_ERROR, "network fail"); + break; + case ExceptionCodes::PlatformWrongStateException: + errorObject = JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::UNKNOWN_ERROR, "service not available"); + break; + default: + errorObject = JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::UNKNOWN_ERROR, "Unknown error"); + break; + } + + m_callbackManager->callOnError(errorObject); + } + + LogDebug(">>>"); +} + +void GeocoderController::setCallback(const JSCallbackManagerPtr &callbackManager) { + m_callbackManager = callbackManager; +} + +JSCallbackManagerPtr GeocoderController::getCallback() const { + return m_callbackManager; +} + +} +} + diff --git a/src/standards/Tizen/Geocoder/GeocoderController.h b/src/standards/Tizen/Geocoder/GeocoderController.h new file mode 100644 index 0000000..4c9a613 --- /dev/null +++ b/src/standards/Tizen/Geocoder/GeocoderController.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* + * @author sangtai kim(Sangtai.kim@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTPLUGINS_TIZEN_GEOCODER_CONTROLLER_H_ +#define WRTPLUGINS_TIZEN_GEOCODER_CONTROLLER_H_ + +#include +#include + +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + + using namespace WrtDeviceApis::CommonsJavaScript; + +class GeocoderController : + public WrtDeviceApis::Commons::EventAnswerReceiver< Api::Geocoder::EventGeocoder> +{ + public: + explicit GeocoderController(const JSCallbackManagerPtr &callbackManager); + virtual ~GeocoderController(); + void setCallback(const JSCallbackManagerPtr &callbackManager ); + JSCallbackManagerPtr getCallback() const; + + protected: + void OnAnswerReceived(const Api::Geocoder::EventGeocoderPtr &event); + + private: + JSCallbackManagerPtr m_callbackManager; +}; + +} +} // WrtPlugins + +#endif //WRTPLUGINS_TIZEN_GEOCODER_CONTROLLER_H_ diff --git a/src/standards/Tizen/Geocoder/JSAddress.cpp b/src/standards/Tizen/Geocoder/JSAddress.cpp new file mode 100644 index 0000000..80c152c --- /dev/null +++ b/src/standards/Tizen/Geocoder/JSAddress.cpp @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* + * @file JSAcceleration.cpp + * @author + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include +#include +#include "JSAddress.h" + +namespace TizenApis { +namespace Tizen1_0 { + +using namespace WrtDeviceApis; +using namespace Api::Geocoder; + +//namespace { +#define GEOCODER_COUNTRY "country" +#define GEOCODER_REGION "region" +#define GEOCODER_COUNTY "county" +#define GEOCODER_CITY "city" +#define GEOCODER_STREET "street" +#define GEOCODER_STREET_NUMBER "streetNumber" +#define GEOCODER_PREMISES "premises" +#define GEOCODER_ADDITIONAL_INFORMATION "additionalInformation" +#define GEOCODER_POSTAL_CODE "postalCode" +//} //private namespace + +JSClassDefinition JSAddress::m_classInfo = { + 0, + kJSClassAttributeNone, + "address", + 0, + m_property, + 0, + initialize, + finalize, + NULL, //HasProperty, + getProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, NULL, //ConvertToType + }; + +JSStaticValue JSAddress::m_property[] = { + { GEOCODER_COUNTRY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { GEOCODER_REGION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { GEOCODER_COUNTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { GEOCODER_CITY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { GEOCODER_STREET, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { GEOCODER_STREET_NUMBER, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { GEOCODER_PREMISES, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { GEOCODER_ADDITIONAL_INFORMATION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { GEOCODER_POSTAL_CODE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSAddress::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSAddress::getClassInfo() { + return &m_classInfo; +} + +JSClassRef JSAddress::m_jsClassRef = JSClassCreate(JSAddress::getClassInfo()); + +JSObjectRef JSAddress::createJSObject(JSContextRef context, const GeocoderProperties &geocoderProperties) { + LogDebug("<<< context:" << context); + + std::auto_ptr accProps(new GeocoderProperties(geocoderProperties)); + JSAddressPriv *priv = new JSAddressPriv(context, accProps.get()); + accProps.release(); + if (!priv) { + ThrowMsg(Commons::NullPointerException, "Can not new an object"); + } + + LogDebug(">>>"); + return JSObjectMake(context, getClassRef(), priv); +} + +void JSAddress::initialize(JSContextRef context, JSObjectRef object) { + LogDebug("Entered. Nothing to do."); +} + +void JSAddress::finalize(JSObjectRef object) { + LogDebug("Entered"); + JSAddressPriv* priv = static_cast (JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting acceleration object"); + delete priv; +} + +JSValueRef JSAddress::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) { + LogDebug("<<< object" << object); + + JSAddressPriv *priv = static_cast (JSObjectGetPrivate(object)); + assert(priv && "Private object not set."); + + Try { + GeocoderProperties *geocoderProperties = priv->getObject(); + WrtDeviceApis::CommonsJavaScript::Converter convert(context); + + + //TODO Add checking NULL String 2011.09.15 + JSValueRef retValue; + if (JSStringIsEqualToUTF8CString(propertyName, GEOCODER_ADDITIONAL_INFORMATION)) { + LogDebug("propertyName: " << GEOCODER_ADDITIONAL_INFORMATION); + LogDebug("geocoderProperties->strAdditionalInformation:[" << geocoderProperties->strAdditionalInformation << "]"); + retValue = convert.toJSValueRef(geocoderProperties->strAdditionalInformation); + } else if (JSStringIsEqualToUTF8CString(propertyName, GEOCODER_CITY)) { + LogDebug("propertyName: " << GEOCODER_CITY); + LogDebug("geocoderProperties->strCity:[" << geocoderProperties->strCity << "]"); + retValue = convert.toJSValueRef(geocoderProperties->strCity); + } else if (JSStringIsEqualToUTF8CString(propertyName, GEOCODER_COUNTRY)) { + LogDebug("propertyName: " << GEOCODER_COUNTRY); + LogDebug("geocoderProperties->strCountryCode:[" << geocoderProperties->strCountry <<"]"); + retValue = convert.toJSValueRef(geocoderProperties->strCountry); + } else if (JSStringIsEqualToUTF8CString(propertyName, GEOCODER_COUNTY)) { + LogDebug("propertyName: " << GEOCODER_COUNTY); + LogDebug("geocoderProperties->strCounty:[" << geocoderProperties->strCounty << "]"); + retValue = convert.toJSValueRef(geocoderProperties->strCounty); + } else if (JSStringIsEqualToUTF8CString(propertyName, GEOCODER_POSTAL_CODE)) { + LogDebug("propertyName: " << GEOCODER_POSTAL_CODE); + LogDebug("geocoderProperties->strPostalCode:[" << geocoderProperties->strPostalCode << "]"); + retValue = convert.toJSValueRef(geocoderProperties->strPostalCode); + } else if (JSStringIsEqualToUTF8CString(propertyName, GEOCODER_PREMISES)) { + LogDebug("propertyName: " << GEOCODER_PREMISES); + LogDebug("geocoderProperties->strBuildingNumber:[" << geocoderProperties->strPremises << "]"); + retValue = convert.toJSValueRef(geocoderProperties->strPremises); + } else if (JSStringIsEqualToUTF8CString(propertyName, GEOCODER_REGION)) { + LogDebug("propertyName: " << GEOCODER_REGION); + LogDebug("geocoderProperties->strState:[" << geocoderProperties->strRegion << "]"); + retValue = convert.toJSValueRef(geocoderProperties->strRegion); + } else if (JSStringIsEqualToUTF8CString(propertyName, GEOCODER_STREET)) { + LogDebug("propertyName: " << GEOCODER_STREET); + LogDebug("geocoderProperties->strStreet:[" << geocoderProperties->strStreet << "]"); + retValue = convert.toJSValueRef(geocoderProperties->strStreet); + } else if (JSStringIsEqualToUTF8CString(propertyName, GEOCODER_STREET_NUMBER)) { + LogDebug("propertyName: " << GEOCODER_STREET_NUMBER); + LogDebug("geocoderProperties->strStreetNumber:[" << geocoderProperties->strStreetNumber <<"]"); + retValue = convert.toJSValueRef(geocoderProperties->strStreetNumber); + } else { + LogDebug(">>> make undefined"); + return JSValueMakeUndefined(context); + } + + LogDebug(">>>"); + return retValue; + }Catch (Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + + return NULL; +} + +bool JSAddress::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) { +return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +} +} //WrtPlugins + diff --git a/src/standards/Tizen/Geocoder/JSAddress.h b/src/standards/Tizen/Geocoder/JSAddress.h new file mode 100644 index 0000000..6b3f5ad --- /dev/null +++ b/src/standards/Tizen/Geocoder/JSAddress.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* + * @file JSAddress.h + * @author + * @version 0.1 + * @brief + */ + +#ifndef WRTPLUGINS_TIZEN_JS_ADDRESS_H_ +#define WRTPLUGINS_TIZEN_JS_ADDRESS_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSAddressPriv; + +class JSAddress +{ +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + /** + * create an JSObject for callback function(onAnswerReceived). + */ + static JSObjectRef createJSObject(JSContextRef context, + const Api::Geocoder::GeocoderProperties &geocodoerProperties); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; + +} +} //WrtPlugins + +#endif + diff --git a/src/standards/Tizen/Geocoder/JSCoordinates.cpp b/src/standards/Tizen/Geocoder/JSCoordinates.cpp new file mode 100644 index 0000000..17b7fc3 --- /dev/null +++ b/src/standards/Tizen/Geocoder/JSCoordinates.cpp @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* + * @file JSCoordinates.cpp + * @author + * @version 0.1 + * @brief Implementation of the JSCoordinates class + */ + +#include "JSCoordinates.h" + +#include +#include +#include +#include +#include +//#include + +namespace TizenApis { +namespace Tizen1_0 { + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace Api::Geocoder; + +//namespace { + #define COORDINATE_LATITUDE "latitude" + #define COORDINATE_LONGITUDE "longitude" + #define COORDINATE_ALTITUDE "altitude" + #define COORDINATE_ACCURACY "accuracy" + #define COORDINATE_ALTITUDE_ACC "altitudeAccuracy" + #define COORDINATE_HEADING "heading" + #define COORDINATE_SPEED "speed" +//} // private namespace + +JSClassRef JSCoordinates::m_jsClassRef = NULL; + +JSClassDefinition JSCoordinates::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "Coordinates", + 0, + m_property, + 0, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + hasInstance, + NULL, //convertToType +}; + +JSStaticValue JSCoordinates::m_property[] = +{ + {COORDINATE_LATITUDE, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {COORDINATE_LONGITUDE, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {COORDINATE_ALTITUDE, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {COORDINATE_ACCURACY, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {COORDINATE_ALTITUDE_ACC, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {COORDINATE_HEADING, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {COORDINATE_SPEED, getProperty, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSCoordinates::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +JSObjectRef JSCoordinates::createJSObject(JSContextRef context, const GeocoderProperties &geocoderProperties) { + std::auto_ptr < GeocoderProperties > posProps(new GeocoderProperties(geocoderProperties)); + JSCoordinatesPriv *priv = new JSCoordinatesPriv(context, posProps.get()); + posProps.release(); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassDefinition* JSCoordinates::getClassInfo() { + return &m_classInfo; +} + +void JSCoordinates::initialize(JSContextRef context, JSObjectRef object) { + LogDebug("Entered. Nothing to do."); +} + +void JSCoordinates::finalize(JSObjectRef object) { + LogDebug("Entered"); + JSCoordinatesPriv* priv = static_cast (JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting coordinates object"); + delete priv; +} + +JSValueRef JSCoordinates::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) { + LogDebug("<<< "); + + JSCoordinatesPriv *priv = static_cast (JSObjectGetPrivate(object)); + assert(priv && "Private object not set."); + + JSValueRef retVal = NULL; + + Try{ + GeocoderProperties *props = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, COORDINATE_LATITUDE)) { + LogDebug(COORDINATE_LATITUDE << ":" << props->latitude); + retVal = convert.toJSValueRef(props->latitude); + } else if (JSStringIsEqualToUTF8CString(propertyName, COORDINATE_LONGITUDE)) { + LogDebug(COORDINATE_LONGITUDE << ":" << props->longitude); + retVal = convert.toJSValueRef(props->longitude); + } else if (JSStringIsEqualToUTF8CString(propertyName, COORDINATE_ALTITUDE)) { + LogDebug(COORDINATE_ALTITUDE << ":" << props->altitude); + retVal = convert.toJSValueRef(props->altitude); + } else if (JSStringIsEqualToUTF8CString(propertyName, COORDINATE_ACCURACY)) { + LogDebug(COORDINATE_ACCURACY << ":" << props->accuracy); + retVal = convert.toJSValueRef(props->accuracy); + } else if (JSStringIsEqualToUTF8CString(propertyName, COORDINATE_ALTITUDE_ACC)) { + LogDebug(COORDINATE_ALTITUDE_ACC << ":" << props->altitudeAccuracy); + retVal = convert.toJSValueRef(props->altitudeAccuracy); + } else if (JSStringIsEqualToUTF8CString(propertyName, COORDINATE_HEADING)) { + LogDebug(COORDINATE_HEADING << ":" << props->heading); + retVal = convert.toJSValueRef(props->heading); + } else if (JSStringIsEqualToUTF8CString(propertyName, COORDINATE_SPEED)) { + LogDebug(COORDINATE_SPEED << ":" << props->speed); + retVal = convert.toJSValueRef(props->speed); + }else{ + retVal = JSValueMakeUndefined(context); + } + }Catch (Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSDOMExceptionFactory::UnknownException.make(context, exception); + } + + LogDebug(">>>"); + return retVal; +} + +bool JSCoordinates::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception){ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +} // Tizen1_0 +} // WrtPlugins + diff --git a/src/standards/Tizen/Geocoder/JSCoordinates.h b/src/standards/Tizen/Geocoder/JSCoordinates.h new file mode 100644 index 0000000..e6509ca --- /dev/null +++ b/src/standards/Tizen/Geocoder/JSCoordinates.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +/* + * @file JSCoordinates.h + * @author + * @version 0.1 + * @brief Declaration of the JSCoordiates class + */ + +#ifndef WRTPLUGINS_TIZEN_JS_COORDINATES_H_ +#define WRTPLUGINS_TIZEN_JS_COORDINATES_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSCoordinatesPriv; + +class JSCoordinates { +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, const Api::Geocoder::GeocoderProperties &geocoderProperties); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; + +} // Tizen1_0 +} // WrtPlugins + +#endif + diff --git a/src/standards/Tizen/Geocoder/JSGeocoder.cpp b/src/standards/Tizen/Geocoder/JSGeocoder.cpp new file mode 100644 index 0000000..15e6edc --- /dev/null +++ b/src/standards/Tizen/Geocoder/JSGeocoder.cpp @@ -0,0 +1,523 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * @file JSGeocoder.cpp + * @author Sangtai Kim (sangtai.kim@samsung.com) + * @version 0.1 + * @brief Implementation of the JSGeocoder class + */ + +#include "JSGeocoder.h" +#include "GeocoderController.h" + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include "plugin_config.h" + +using namespace std; +using namespace DPL; +//using namespace TizenApis::Tizen1_0::Platform; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Tizen1_0::Api::Geocoder; +using namespace TizenApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { + +//#define GET_ADDRESS_ARGUMENT_COUNT 4 +//#define GET_POSITION_ARGUMENT_COUNT 3 + + const std::string JSGeocoder::JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT = "Invalid argument"; + +const std::string JSGeocoder::GEOCODER_ADDRESS_COUNTRY = "country"; +const std::string JSGeocoder::GEOCODER_ADDRESS_REGION = "region"; +const std::string JSGeocoder::GEOCODER_ADDRESS_COUNTY = "county"; +const std::string JSGeocoder::GEOCODER_ADDRESS_CITY = "city"; +const std::string JSGeocoder::GEOCODER_ADDRESS_STREET = "street"; +const std::string JSGeocoder::GEOCODER_ADDRESS_STREET_NUMBER = "streetNumber"; +const std::string JSGeocoder::GEOCODER_ADDRESS_PREMISES = "premises"; +const std::string JSGeocoder::GEOCODER_ADDRESS_ADDTIONAL_INFORMATION = "additionalInformation"; +const std::string JSGeocoder::GEOCODER_ADDRESS_POSTAL_CODE = "postalCode"; + +const std::string JSGeocoder::GEOCODER_COORDINATES_LATITUDE = "latitude"; +const std::string JSGeocoder::GEOCODER_COORDINATES_LONGITUDE = "longitude"; + +const std::string JSGeocoder::gGeocoderAddressArray[] = { + GEOCODER_ADDRESS_COUNTRY, + GEOCODER_ADDRESS_REGION, + GEOCODER_ADDRESS_COUNTY, + GEOCODER_ADDRESS_CITY, + GEOCODER_ADDRESS_STREET, + GEOCODER_ADDRESS_STREET_NUMBER, + GEOCODER_ADDRESS_PREMISES, + GEOCODER_ADDRESS_ADDTIONAL_INFORMATION, + GEOCODER_ADDRESS_POSTAL_CODE +}; + +JSClassRef JSGeocoder::m_jsClassRef = NULL; + +JSClassDefinition JSGeocoder::m_classInfo = { + 0, + kJSClassAttributeNone, + "Geocoder", + NULL, + NULL, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty,Geolocation + NULL, //getPropertyNames, + NULL, + NULL, + hasInstance, + NULL +}; + +JSStaticFunction JSGeocoder::m_function[] = { + { "geocode", JSGeocoder::geocode, kJSPropertyAttributeNone }, + { "reverseGeocode", JSGeocoder::reverseGeocode, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef JSGeocoder::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSGeocoder::getClassInfo() { + return &m_classInfo; +} + +void JSGeocoder::initialize(JSContextRef context, JSObjectRef object) { + JSGeocoderPriv* priv = static_cast (JSObjectGetPrivate(object)); + assert(!priv && "Invalid object creation."); + IGeocoderPtr geocoder(GeocoderFactory::getInstance().getGeocoder()); + priv = new JSGeocoderPriv(context, geocoder); + if (!JSObjectSetPrivate(object, static_cast (priv))) { + LogError("Object can't store private data."); + delete priv; + } +} + +void JSGeocoder::finalize(JSObjectRef object) { + JSGeocoderPriv* priv = static_cast (JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting gallery"); + delete priv; +} + +GeocoderProperties JSGeocoder::toGeocoderProperties(JSContextRef context, const JSValueRef& arg){ + GeocoderProperties properties; + + CommonsJavaScript::Converter converter(context); + + JSValueRef valueRefLatitude = JSUtils::getJSProperty(context, arg, GEOCODER_COORDINATES_LATITUDE); + if(valueRefLatitude!=NULL && JSValueIsNumber(context, valueRefLatitude)){ + properties.latitude = converter.toDouble(valueRefLatitude); + }else{ + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + JSValueRef valueRefLongitude = JSUtils::getJSProperty(context, arg, GEOCODER_COORDINATES_LONGITUDE); + if(valueRefLongitude!=NULL && JSValueIsNumber(context, valueRefLongitude)){ + properties.longitude = converter.toDouble(valueRefLongitude); + }else{ + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + return properties; +} + +bool JSGeocoder::hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSGeocoder::getAddressByCoordinates(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) { + + JSGeocoderPriv *priv = static_cast (JSObjectGetPrivate(thisObject)); + + assert(priv && "Invalid private pointer."); + CommonsJavaScript::Converter converter(context); + Validator check(context, exception); + + JSValueRef onSuccess = NULL; + JSValueRef onError = NULL; + + GeocoderProperties properties; + Try{ + properties = toGeocoderProperties(context, arguments[0]); + }Catch(WrtDeviceApis::Commons::InvalidArgumentException){ + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT); + } + + double latitude = properties.latitude; + double longitude = properties.longitude; + + if(argumentCount==2){ + onSuccess = arguments[1]; + onError = NULL; + if(check.isCallback(onSuccess) != true){ + LogError("Wrong callbacks parameters"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT); + } + }else if(argumentCount==3){ + onSuccess = arguments[1]; + onError = arguments[2]; + if(check.isCallback(onSuccess)!=true || check.isCallback(onError)!=true){ + LogError("Wrong callbacks parameters"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT); + } + }else{ + LogError("Wrong callbacks parameters"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT); + } + + return getAddressInternal(context, latitude, longitude, thisObject, onSuccess, onError); +} + + +JSValueRef JSGeocoder::getAddressInternal(JSContextRef context, double latitude, double longitude, JSObjectRef thisObject, JSValueRef onSuccess, JSValueRef onError){ + LogDebug(" <<< latitude:" << latitude << ", longitude:" << longitude); + + JSGeocoderPriv *priv = static_cast (JSObjectGetPrivate(thisObject)); + JSContextRef gContext = priv->getContext(); + assert(priv && "Invalid private pointer."); + + JSCallbackManagerPtr cbm(JSCallbackManager::createObject(priv->getContext(), onSuccess, onError)); + cbm->setObject(thisObject); + + EventGeocoderPtr event(new EventGeocoder()); + SharedPtr < IEventController > eventContr = StaticPointerCast (event); + JSObjectRef pendingOperation = CommonsJavaScript::makePendingOperation(gContext, event); + + Try{ + IGeocoderPtr geocoder(priv->getObject()); + + event->setPrivateData(StaticPointerCast (cbm)); + event->setForAsynchronousCall(new GeocoderController(cbm)); + event->setLatitude(latitude); + event->setLongitude(longitude); + event->setEventType(EventGeocoder::GEOCODER_EVENT_GET_ADDRESS); + + geocoder->getAddressFromPosition(event); + }Catch (WrtDeviceApis::Commons::PendingOperationException){ + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT)); + }Catch (WrtDeviceApis::Commons::ConversionException){ + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT)); + }Catch (WrtDeviceApis::Commons::InvalidArgumentException){ + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT)); + }Catch(WrtDeviceApis::Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage() << " Code: " << _rethrown_exception.getCode()); + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::UNKNOWN_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT )); + } + + LogInfo(">>>"); + return pendingOperation; +} + + + +JSValueRef JSGeocoder::getAddressByPosition(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) { + + JSValueRef onSuccess = NULL; + JSValueRef onError = NULL; + + JSGeocoderPriv *priv = static_cast (JSObjectGetPrivate(thisObject)); + + assert(priv && "Invalid private pointer."); + CommonsJavaScript::Converter converter(context); + Validator check(context, exception); + + if(argumentCount==3){ + onSuccess = arguments[2]; + onError = NULL; + if(check.isCallback(onSuccess) != true){ + LogError("Wrong callbacks parameters"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT); + } + }else if(argumentCount==4){ + onSuccess = arguments[2]; + onError = arguments[3]; + if(check.isCallback(onSuccess)!=true || check.isCallback(onError)!=true){ + LogError("Wrong callbacks parameters"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT); + } + }else{ + LogError("Wrong callbacks parameters"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT); + } + + //check is valid ratitude and longitude + if(JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0])){ + LogError("[ERROR]Wrong latitude"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT); + } + + if(JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1])){ + LogError("[ERROR]Wrong longitude"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT); + } + + double l_latitude = 0.0; + double l_longitude = 0.0; + + Try{ + l_latitude = static_cast(converter.toDouble(arguments[0])); + l_longitude = static_cast(converter.toDouble(arguments[1])); + }Catch(WrtDeviceApis::Commons::ConversionException){ + LogError("[ERROR]Conversion Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT); + } + + return getAddressInternal(context, l_latitude, l_longitude, thisObject, onSuccess, onError); +} + +JSValueRef JSGeocoder::geocode(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) { + LogInfo("<<<"); + LogDebug("arumentConunt:" << argumentCount); + + JSGeocoderPriv *priv = static_cast (JSObjectGetPrivate(thisObject)); + assert(priv && "Invalid private pointer."); + + AceSecurityStatus status = GEOCODER_CHECK_ACCESS(priv->getContext(), GEOCODER_FUNCTION_API_REVERSE_GEOCODE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + CommonsJavaScript::Converter converter(context); + Validator check(context, exception); + + //argument[0] : Address + //argument[1] : success callback + //argument[2] : error callback //Optional + //OR + //argument[0] : AddressString + //argument[1] : success callback + //argument[2] : error callback //Optional + + if(argumentCountsetAddressString(strAddress); + }else{ //TYPE is A + JSValueRef addressUnit = NULL; + int sizeOfGeocoderAddressUnit = sizeof(gGeocoderAddressArray) / sizeof(std::string); + LogDebug("sizeOfGeocoderAddressUnit : " << sizeOfGeocoderAddressUnit); + + std::map addressMap; + + //check is valid ratitude and address + if ((!JSValueIsNull(context, arguments[0]) && !JSValueIsUndefined(context, arguments[0]))){ + for(int i=0; i(gGeocoderAddressArray[i], strAddress)); + }else{ + } + + addressUnit = NULL; + } + }else{ + LogError("[ERROR]Wrong Address"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT); + } + + setAddressData(event, addressMap); + } //else + + JSCallbackManagerPtr cbm(JSCallbackManager::createObject(priv->getContext(), onSuccess, onError)); + cbm->setObject(thisObject); + + SharedPtr < IEventController > eventContr = StaticPointerCast (event); + JSObjectRef pendingOperation = CommonsJavaScript::makePendingOperation(context, event); + + Try{ + IGeocoderPtr geocoder(priv->getObject()); + + event->setPrivateData(StaticPointerCast (cbm)); + event->setForAsynchronousCall(new GeocoderController(cbm)); + event->setEventType(EventGeocoder::GEOCODER_EVENT_GET_POSITION); + + geocoder->getPositionFromAddress(event); + }Catch (WrtDeviceApis::Commons::PendingOperationException){ + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT )); + }Catch (WrtDeviceApis::Commons::ConversionException){ + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT )); + }Catch (WrtDeviceApis::Commons::InvalidArgumentException){ + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT )); + }Catch(WrtDeviceApis::Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage() << " Code: " << _rethrown_exception.getCode()); + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT )); + } + + LogInfo(">>>"); + return pendingOperation; +} //geocode + +JSValueRef JSGeocoder::reverseGeocode (JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) { + LogInfo("<<<"); + LogDebug("arumentConunt:" << argumentCount); + + JSGeocoderPriv *priv = static_cast (JSObjectGetPrivate(thisObject)); + AceSecurityStatus status = GEOCODER_CHECK_ACCESS(priv->getContext(), GEOCODER_FUNCTION_API_GEOCODE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + //argument[0] : latitude + //argument[1] : longitude + //argument[2] : success callback + //argument[3] : error callback //optional + //OR + //argument[0] : Coordinates + //argument[1] : success callback + //argument[2] : error callback //optional + if(JSValueIsObject(context, arguments[0]) == true){ //argument[0] is Coordinates + return getAddressByCoordinates(context, thisObject, argumentCount, arguments, exception); + }else{ + return getAddressByPosition(context, thisObject, argumentCount, arguments, exception); + } +} //reverseGeocode + +int JSGeocoder::setAddressData(const Api::Geocoder::EventGeocoderPtr& event, std::map& addressMap) +{ + std::map::iterator it; + + it = addressMap.find(GEOCODER_ADDRESS_COUNTRY); + if(it != addressMap.end()){ + event->setCountry(it->second); + } + + it = addressMap.find(GEOCODER_ADDRESS_REGION); + if(it != addressMap.end()){ + event->setRegion(it->second); + } + + it = addressMap.find(GEOCODER_ADDRESS_COUNTY); + if(it != addressMap.end()){ + event->setCounty(it->second); + } + + it = addressMap.find(GEOCODER_ADDRESS_CITY); + if(it != addressMap.end()){ + event->setCity(it->second); + } + + it = addressMap.find(GEOCODER_ADDRESS_STREET); + if(it != addressMap.end()){ + event->setStreet(it->second); + } + + it = addressMap.find(GEOCODER_ADDRESS_STREET_NUMBER); + if(it != addressMap.end()){ + event->setStreetNumber(it->second); + } + + it = addressMap.find(GEOCODER_ADDRESS_PREMISES); + if(it != addressMap.end()){ + event->setPremises(it->second); + } + + it = addressMap.find(GEOCODER_ADDRESS_ADDTIONAL_INFORMATION); + if(it != addressMap.end()){ + event->setAdditionalInformation(it->second); + } + + it = addressMap.find(GEOCODER_ADDRESS_POSTAL_CODE); + if(it != addressMap.end()){ + event->setPostalCode(it->second); + } + + return 0; +} + +}// Tizen1_0 +}// WrtPlugins diff --git a/src/standards/Tizen/Geocoder/JSGeocoder.h b/src/standards/Tizen/Geocoder/JSGeocoder.h new file mode 100644 index 0000000..27ef570 --- /dev/null +++ b/src/standards/Tizen/Geocoder/JSGeocoder.h @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* + * @file JSGeolocation.h + * @author + * @version 0.1 + * @brief Declaration of the JSGeolocation class + */ + +#ifndef WRTPLUGINS_TIZEN_JS_GEOLOCATION_H_ +#define WRTPLUGINS_TIZEN_JS_GEOLOCATION_H_ + +#include +#include +#include + +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSGeocoderPriv; + +class JSGeocoder { +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + /** + * Get address from postion. + */ + static JSValueRef geocode(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Get address from postion. + */ + static JSValueRef reverseGeocode(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + + static int setAddressData(const Api::Geocoder::EventGeocoderPtr& event, std::map& addressMap); + + static JSValueRef getAddressByCoordinates(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef getAddressByPosition(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef getAddressInternal(JSContextRef context, double latitude, double longitude, JSObjectRef thisObject, JSValueRef onSuccess, JSValueRef onError); + static Api::Geocoder::GeocoderProperties toGeocoderProperties(JSContextRef context, const JSValueRef& arg); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + static JSClassRef m_jsClassRef; + +private: + static const std::string JSGEOCODER_EXCEPTION_STRING_INVALID_ARGUMENT; + static const std::string GEOCODER_ADDRESS_COUNTRY; + static const std::string GEOCODER_ADDRESS_REGION; + static const std::string GEOCODER_ADDRESS_COUNTY; + static const std::string GEOCODER_ADDRESS_CITY; + static const std::string GEOCODER_ADDRESS_STREET; + static const std::string GEOCODER_ADDRESS_STREET_NUMBER; + static const std::string GEOCODER_ADDRESS_PREMISES; + static const std::string GEOCODER_ADDRESS_ADDTIONAL_INFORMATION; + static const std::string GEOCODER_ADDRESS_POSTAL_CODE; + + static const std::string GEOCODER_COORDINATES_LATITUDE; + static const std::string GEOCODER_COORDINATES_LONGITUDE; + + static const std::string gGeocoderAddressArray[]; + + enum{ + GET_POSITION_ARGUMENT_COUNT = 2, + GET_ADDRESS_ARGUMENT_COUNT = 3 + }; + +}; + +} //Tizen1_0 +} //WrtPlugins + +#endif + diff --git a/src/standards/Tizen/Geocoder/config.xml b/src/standards/Tizen/Geocoder/config.xml new file mode 100644 index 0000000..b3b6a29 --- /dev/null +++ b/src/standards/Tizen/Geocoder/config.xml @@ -0,0 +1,19 @@ + + + + libwrt-plugins-tizen-1.0-geocoder.so + geocoder.install.uri + SAMSUNG plugin group + SAMSUNG certificate authority + AAAABBBBCCCCDDDEEEE0000 + + + http://tizen.org/api/geocoder + + geocoder + + + + + + diff --git a/src/standards/Tizen/Geocoder/plugin_config.cpp b/src/standards/Tizen/Geocoder/plugin_config.cpp new file mode 100755 index 0000000..efceb97 --- /dev/null +++ b/src/standards/Tizen/Geocoder/plugin_config.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "plugin_config.h" + +#define GEOCODER_FEATURE_API "http://tizen.org/api/geocoder" +#define GEOCODER_DEVICE_CAP_GEOCODER "geocoder" + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { + namespace Tizen1_0 { + + const char* GEOCODER_FUNCTION_API_GEOCODE = "geocode"; + const char* GEOCODER_FUNCTION_API_REVERSE_GEOCODE = "reverseGeocode"; + + static Commons::FunctionMapping createGeocoderFunctions(); + + static Commons::FunctionMapping GeocoderFunctions = createGeocoderFunctions(); + + DEFINE_FUNCTION_GETTER(Geocoder, GeocoderFunctions) + ; + + static Commons::FunctionMapping createGeocoderFunctions() { + /** + * Device capabilities + */ + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_GEOCODER, GEOCODER_DEVICE_CAP_GEOCODER); + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_GEOCODER); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_GEOCODER, DEVICE_CAP_GEOCODER); + + /** + * Api Features + */ + ACE_CREATE_FEATURE(FEATURE_GEOCODER, GEOCODER_FEATURE_API); + ACE_CREATE_FEATURE_LIST(GEOCODER_FEATURES_GEOCODER); + ACE_ADD_API_FEATURE(GEOCODER_FEATURES_GEOCODER, FEATURE_GEOCODER); + + /** + * Functions + */ + FunctionMapping geocoderMapping; + + //geocode + AceFunction geocodeFunc = ACE_CREATE_FUNCTION( + FUNCTION_GEOCODE, + GEOCODER_FUNCTION_API_GEOCODE, + GEOCODER_FEATURES_GEOCODER, + DEVICE_LIST_GEOCODER); + + geocoderMapping.insert(std::make_pair(GEOCODER_FUNCTION_API_GEOCODE, geocodeFunc)); + + //reverseGeocode + AceFunction reverseGeocodeFunc = ACE_CREATE_FUNCTION( + FUNCTION_REVERSE_GEOCODE, + GEOCODER_FUNCTION_API_REVERSE_GEOCODE, + GEOCODER_FEATURES_GEOCODER, + EMPTY_DEVICE_LIST); + + geocoderMapping.insert(std::make_pair(GEOCODER_FUNCTION_API_REVERSE_GEOCODE, reverseGeocodeFunc)); + + return geocoderMapping; + } + + } // namespace Tizen1_0 +} // namespace WrtPlugins diff --git a/src/standards/Tizen/Geocoder/plugin_config.h b/src/standards/Tizen/Geocoder/plugin_config.h new file mode 100755 index 0000000..cd74c6e --- /dev/null +++ b/src/standards/Tizen/Geocoder/plugin_config.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _GEOCODER_PLUGIN_CONFIG_H_ +#define _GEOCODER_PLUGIN_CONFIG_H_ + +#include + +namespace TizenApis { +namespace Tizen1_0 { + +extern const char* GEOCODER_FUNCTION_API_GEOCODE; +extern const char* GEOCODER_FUNCTION_API_REVERSE_GEOCODE; + +DECLARE_FUNCTION_GETTER(Geocoder); + +#define GEOCODER_CHECK_ACCESS(globalContext, functionName) \ + aceCheckAccess > ( \ + globalContext, \ + getGeocoderFunctionData, \ + functionName) + +} +} + +#endif // _GEOCODER_PLUGIN_CONFIG_H_ diff --git a/src/standards/Tizen/Geocoder/plugin_initializer.cpp b/src/standards/Tizen/Geocoder/plugin_initializer.cpp new file mode 100644 index 0000000..4a9d67c --- /dev/null +++ b/src/standards/Tizen/Geocoder/plugin_initializer.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#include +#include +#include "JSGeocoder.h" + +#define WRT_JS_EXTENSION_OBJECT_TIZEN "tizen" + +void on_widget_start_callback(int widgetId, JavaScriptContext context, const engine_interface_t *interface) { + LogDebug("[Tizen\\Geocoder] on_widget_start_callback ("< +#include +#include +#include +#include +#include + +#include "JSTizenLog.h" + +#include + +#ifdef LOG_TAG +#undef LOG_TAG +#endif + +#define LOG_TAG "TIZEN" + +#define EXCEPTION_COLOR "\033[1;31;40m" //bold and red +#define ASSERT_COLOR "\033[1;31;40m" //bold and red + +#define GREEN_COLOR "\033[0;32;40m" //normal and green +#define NORMAL_COLOR "\033[0m" //system default +#define RED_COLOR "\033[0;31;40m" //normal and red +#define YELLOW_COLOR "\033[0;33m" //normal and yellow +#define BLUE_COLOR "\033[0;34m" //normal and blue +#define MAGENTA_COLOR "\033[0;35;40m" //normal and magenta +#define CYAN_COLOR "\033[0;36;40m" //normal and cyan + +#define TIZEN_DEBUG(FM,ARG...) {LOGD("%s[%s]%s" FM, GREEN_COLOR, __FUNCTION__, NORMAL_COLOR, ##ARG);} +#define TIZEN_INFO(FM,ARG...) {LOGI("%s[%s]%s" FM, CYAN_COLOR, __FUNCTION__, NORMAL_COLOR, ##ARG);} +#define TIZEN_WANING(FM,ARG...) {LOGW("%s[%s]%s" FM, YELLOW_COLOR, __FUNCTION__, NORMAL_COLOR, ##ARG);} +#define TIZEN_ERROR(FM,ARG...) {LOGE("%s[%s]%s" FM, RED_COLOR, __FUNCTION__, NORMAL_COLOR, ##ARG);} + +namespace TizenApis { +namespace Tizen1_0 { + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis; + +JSClassDefinition JSTizenLog::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "log", + 0, + NULL, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType +}; + +const JSClassRef JSTizenLog::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSTizenLog::getClassInfo() { + return &m_classInfo; +} + +JSStaticFunction JSTizenLog::m_function[] = { + { "debug", JSTizenLog::logDebug, kJSPropertyAttributeNone}, + { "info", JSTizenLog::logInfo, kJSPropertyAttributeNone}, + { "warning", JSTizenLog::logWarning, kJSPropertyAttributeNone}, + { "error", JSTizenLog::logError, kJSPropertyAttributeNone}, + { 0, 0, 0 } +}; + +JSClassRef JSTizenLog::m_jsClassRef = + JSClassCreate(JSTizenLog::getClassInfo()); + + +void JSTizenLog::initialize(JSContextRef context, JSObjectRef object) { +// TIZEN_DEBUG("<<<"); +} + +void JSTizenLog::finalize(JSObjectRef object) { +// TIZEN_DEBUG("<<<"); +} + +JSValueRef JSTizenLog::logDebug(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argc, const JSValueRef argv[], + JSValueRef* exception) { + + CommonsJavaScript::Converter converter(context); + std::string pattern = converter.toString(argv[0]); + + TIZEN_DEBUG("[%s]", pattern.c_str()); + + return JSValueMakeUndefined(context); +} + +JSValueRef JSTizenLog::logInfo(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argc, const JSValueRef argv[], + JSValueRef* exception) { + + CommonsJavaScript::Converter converter(context); + std::string pattern = converter.toString(argv[0]); + + TIZEN_INFO("[%s]", pattern.c_str()); + + return JSValueMakeUndefined(context); +} + +JSValueRef JSTizenLog::logWarning(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argc, const JSValueRef argv[], + JSValueRef* exception) { + + CommonsJavaScript::Converter converter(context); + std::string pattern = converter.toString(argv[0]); + + TIZEN_WANING("[%s]", pattern.c_str()); + + return JSValueMakeUndefined(context); +} + +JSValueRef JSTizenLog::logError(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argc, const JSValueRef argv[], + JSValueRef* exception) { + + CommonsJavaScript::Converter converter(context); + std::string pattern = converter.toString(argv[0]); + + TIZEN_ERROR("[%s]", pattern.c_str()); + + return JSValueMakeUndefined(context); +} + +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Log/JSTizenLog.h b/src/standards/Tizen/Log/JSTizenLog.h new file mode 100644 index 0000000..aa18dd4 --- /dev/null +++ b/src/standards/Tizen/Log/JSTizenLog.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * @file JSTizenLog.h + * @author Sang-tai Kim(sangtai.kim@samsung.com) + * @version 0.1 + */ + + +#ifndef _JS_TIZEN_LOG_H_ +#define _JS_TIZEN_LOG_H_ + +#include + +namespace TizenApis { +namespace Tizen1_0 { + +class DeviceController; + +/** + * @class JSTizenLog + * @brief This class is javascript extenstion + * + */ +class JSTizenLog +{ +public: + static const JSClassDefinition* getClassInfo(); + + /** + * Gets class definition reference. + * @remarks New instance of JSClassRef is created (only once) if none was + * @remarks set before. + * @return Class reference. + */ + static const JSClassRef getClassRef(); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure describes a statically declared function. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * Class definition reference. + */ + + static JSClassRef m_jsClassRef; + + static JSValueRef logDebug(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception); + + static JSValueRef logInfo(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception); + + static JSValueRef logWarning(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception); + + static JSValueRef logError(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception); + +}; + +} + +} + +#endif // _JS_TIZEN_LOG_H_ diff --git a/src/standards/Tizen/Log/config.xml b/src/standards/Tizen/Log/config.xml new file mode 100644 index 0000000..fe6fa61 --- /dev/null +++ b/src/standards/Tizen/Log/config.xml @@ -0,0 +1,23 @@ + + + + libwrt-plugins-tizen-1.0-tizenlog.so + device.install.uri + SAMSUNG plugin group + SAMSUNG certificate authority + AAAABBBBCCCCDDDEEEE0000 + + + + + + + http://tizen.org/api/log + + + + + + + + diff --git a/src/standards/Tizen/Log/plugin_initializer.cpp b/src/standards/Tizen/Log/plugin_initializer.cpp new file mode 100644 index 0000000..eeab032 --- /dev/null +++ b/src/standards/Tizen/Log/plugin_initializer.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "JSTizenLog.h" + +#define WRT_JS_EXTENSION_OBJECT_TIZEN "tizen" + +void on_widget_start_callback(int widgetId, JavaScriptContext context, const engine_interface_t *interface) +{ + LogDebug("[TizenLog] on_widget_start_callback ("< +#include +#include +#include +#include +#include +#include "ConverterMessage.h" +#include "JSMessage.h" +#include "JSMessagePrivateObject.h" +#include "JSRecipientArray.h" +#include "JSMessagingListener.h" +#include +#include "JSMessageAttachment.h" +#include "JSConversation.h" +#include "JSMessageFolder.h" + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +#include +#endif + +using namespace std; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace { +const char* SEND_PROPERTY_ONSUCCESS = "onsuccess"; +const char* SEND_PROPERTY_ONMESSAGESENDSUCCESS = "onmessagesendsuccess"; +const char* SEND_PROPERTY_ONMESSAGESENDERROR = "onmessagesenderror"; +} + +namespace TizenApis { +namespace Tizen1_0 { + +MessageFunctions ConverterMessage::m_callbackNames[MESSAGING_MULTI_FUNTION_MAX] +{ + {"messagesAdded", "messagesUpdated", "messagesRemoved"}, + {"conversationsAdded", "conversationsUpdated", "conversationsRemoved"}, + {"foldersAdded", "foldersUpdated", "foldersRemoved"} +}; + +ConverterMessage::ConverterMessage(JSContextRef context) : + Converter(context) +{ +} + +ConverterMessage::~ConverterMessage() +{ +} + +JSContextRef ConverterMessage::toJSGlobalContext(JSObjectRef arg) +{ + // get private object + WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type* priv = + static_cast::Type*>(JSObjectGetPrivate( + arg)); + if (!priv) { + LogError("Private object not initialized"); + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Private object not initialized"); + } + return priv->getContext(); +} + +JSValueRef ConverterMessage::toJSValueRef(Api::Messaging::FolderType arg) +{ + switch (arg) { + case Api::Messaging::INBOX: + return toJSValueRef(messageFolderInbox); + case Api::Messaging::OUTBOX: + return toJSValueRef(messageFolderOutbox); + case Api::Messaging::DRAFTBOX: + return toJSValueRef(messageFolderDrafts); + case Api::Messaging::SENTBOX: + return toJSValueRef(messageFolderSentbox); + default: + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "folder not supported"); + } +} + +JSValueRef ConverterMessage::toJSValueRef(Api::Messaging::MessageType arg) +{ + switch (arg) { + case Api::Messaging::SMS: + return toJSValueRef(messageTypeSms); + case Api::Messaging::MMS: + return toJSValueRef(messageTypeMms); + case Api::Messaging::EMAIL: + return toJSValueRef(messageTypeEmail); + default: + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "message type not supported"); + } +} + +JSValueRef ConverterMessage::toJSValueRef(const Api::Messaging::IMessagePtr& arg, + Api::Messaging::EventUpdateMessageAnswerReceiver* listener) +{ + switch (arg->getMessageType()) { + case Api::Messaging::SMS: + case Api::Messaging::MMS: + case Api::Messaging::EMAIL: + return JSMessage::createJSObject(m_context, arg, listener); + + default: + LogError("unknown type"); + Throw(WrtDeviceApis::Commons::ConversionException); + } +} + +JSValueRef ConverterMessage::toJSValueRef( + const std::vector& arg, + Api::Messaging::EventUpdateMessageAnswerReceiver* listener) +{ + vector msgsJS; + for (size_t i = 0; i < arg.size(); i++) { + msgsJS.push_back(toJSValueRef(arg[i], listener)); + } + return toJSValueRef(msgsJS); +} + +JSValueRef ConverterMessage::toJSValueRef(const std::vector& conversations) +{ + vector conversationJS; + + for (size_t i = 0; i < conversations.size(); i++) + { + JSValueRef value = JSConversation::createJSObject(m_context, conversations[i]); + conversationJS.push_back(value); + } + + return toJSValueRef(conversationJS); +} + +JSValueRef ConverterMessage::toJSValueRef(const std::vector& messagefolders) +{ + vector messagefolderJS; + + for (size_t i = 0; i < messagefolders.size(); i++) + { + JSValueRef value = JSMessageFolder::createJSObject(m_context, messagefolders[i]); + messagefolderJS.push_back(value); + } + + return toJSValueRef(messagefolderJS); +} + +JSValueRef ConverterMessage::toJSValueRef(const Api::Messaging::MessagePriority& arg) +{ + switch (arg.getPriority()) { + case Api::Messaging::MessagePriority::LOW: + return toJSValueRef(false); + break; + case Api::Messaging::MessagePriority::NORMAL: + return toJSValueRef(false); + break; + case Api::Messaging::MessagePriority::HIGH: + return toJSValueRef(true); + break; + default: + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Unknown priority"); + break; + } +} + +JSValueRef ConverterMessage::keyToJSValue(JSValueRef value, + const string& key) +{ + JSValueRef retVal = NULL; + + if (NULL == value) { + LogError("jsValue null"); + Throw(WrtDeviceApis::Commons::ConversionException); + } + JSObjectRef argObj = JSValueToObject(m_context, value, NULL); + if (NULL == argObj) { + LogError("conversion to jsobject fail"); + Throw(WrtDeviceApis::Commons::ConversionException); + } + const JSStringRef keyJSStr = JSStringCreateWithUTF8CString(key.c_str()); + retVal = JSObjectGetProperty(m_context, argObj, keyJSStr, NULL); + JSStringRelease(keyJSStr); + if (NULL == retVal) { + LogWarning("key \"" << key << "\" not found in JSValue map"); + } + // return NULL if no key in map + return retVal; +} + +Api::Messaging::IMessagePtr ConverterMessage::toIMessage(JSValueRef arg) +{ + return toIMessage(toJSObjectRef(arg)); +} + +Api::Messaging::IMessagePtr ConverterMessage::toIMessage(JSObjectRef arg) +{ + LogDebug("message object=" << arg); + if (!arg) { + LogError("Object is null"); + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Private object not initialized"); + } + Api::Messaging::IMessagePtr retVal; + // get private object + JSMessagePrivateObject* priv = + static_cast(JSObjectGetPrivate(arg)); + if (!priv) { + LogError("Private object not initialized"); + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Private object not initialized"); + } + retVal = priv->getObject(); + if (!retVal) { + LogError("Message private object not initialized"); + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Private object not initialized"); + } + return retVal; +} + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +Api::Messaging::IAttachmentPtr ConverterMessage::toIAttachment(JSValueRef arg) +{ + return toIAttachment(toJSObjectRef(arg)); +} + +Api::Messaging::IAttachmentPtr ConverterMessage::toIAttachment(JSObjectRef arg) +{ + if (!arg) + { + LogError("Object is Null"); + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object not initialized"); + } + + Api::Messaging::IAttachmentPtr retVal; + JSMessageAttachmentPrivate* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + LogError("Private object not initialized"); + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Private object not initialized"); + } + + retVal = priv->getObject(); + if (!retVal) { + LogError("Message private object not initialized"); + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Private object not initialized"); + } + return retVal; +} +#endif + +Api::Messaging::IMessageFolderPtr ConverterMessage::toIMessageFolder(JSValueRef arg) +{ + return toIMessageFolder(toJSObjectRef(arg)); +} + +Api::Messaging::IMessageFolderPtr ConverterMessage::toIMessageFolder(JSObjectRef arg) +{ + if (!arg) + { + LogError("Object is Null"); + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object not initialized"); + } + + Api::Messaging::IMessageFolderPtr retVal; + JSMessageFolderPriv* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + LogError("Private object not initialized"); + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Private object not initialized"); + } + + retVal = priv->getObject(); + if (!retVal) { + LogError("Message private object not initialized"); + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Private object not initialized"); + } + return retVal; +} + +Api::Messaging::Recipients ConverterMessage::toRecipients(JSValueRef arg) +{ + if (JSValueIsObjectOfClass(m_context, arg, + JSRecipientArray::getClassRef())) { + Api::Messaging::RecipientsPtr recipients = + JSRecipientArray::getRecipients(m_context, toJSObjectRef(arg)); + if (!recipients) { + Throw(WrtDeviceApis::Commons::ConversionException); + } + return *recipients; + } + Api::Messaging::Recipients retVal; + // convert JS value to vector of recipient addresses + vector recip = toVectorOfStrings(arg); + retVal.setRecipients(recip); + return retVal; +} + +OnMessagesChanged ConverterMessage::toMessageMultifunctions(JSValueRef argument) +{ + OnMessagesChanged result; + Validator validator(m_context); + JSObjectRef objectCallbacks = toJSObjectRef(argument); + std::string callbackName = toString(argument); + int index = 0; + + LogDebug("Enter\n"); + + for (index = 0; index < MESSAGING_MULTI_FUNTION_MAX; index++) + { + ScopedJSStringRef propName(toJSStringRef(m_callbackNames[index].addedFunction)); + + if (JSObjectHasProperty(m_context, objectCallbacks, propName.get())) + { + LogDebug("Callback name :" << m_callbackNames[index].addedFunction << " " + << m_callbackNames[index].updatedFunction << " " << m_callbackNames[index].removedFunction); + + result.messagesAdded = JSUtils::getJSPropertyOrUndefined(m_context, objectCallbacks, m_callbackNames[index].addedFunction); + result.messagesUpdated = JSUtils::getJSPropertyOrUndefined(m_context, objectCallbacks, m_callbackNames[index].updatedFunction); + result.messagesRemoved = JSUtils::getJSPropertyOrUndefined(m_context, objectCallbacks, m_callbackNames[index].removedFunction); + break; + } + + } + + result.functionIndex = index; + + if ((!validator.isNullOrUndefined(result.messagesAdded) && !validator.isCallback(result.messagesAdded)) || + (!validator.isNullOrUndefined(result.messagesUpdated) && !validator.isCallback(result.messagesUpdated)) || + (!validator.isNullOrUndefined(result.messagesRemoved) && !validator.isCallback(result.messagesRemoved))) + { + LogError("java script call back set error"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + return result; +} + + +std::vector ConverterMessage::toVectorOfFolderTypes( + JSValueRef arg) +{ + return toVectorOfT_(arg, &ConverterMessage::toFolderType, this); +} + +Api::Messaging::FolderType ConverterMessage::toFolderType(const JSValueRef& arg) +{ + // convert JS value to folder type + messageFolders folder = static_cast(toInt(arg)); + switch (folder) { + case messageFolderInbox: + return Api::Messaging::INBOX; + case messageFolderOutbox: + return Api::Messaging::OUTBOX; + case messageFolderDrafts: + return Api::Messaging::DRAFTBOX; + case messageFolderSentbox: + return Api::Messaging::SENTBOX; + default: + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "folder not supported"); + } +} + +Api::Messaging::MessageType ConverterMessage::toMessageType(JSValueRef arg) +{ + return toMessageType(toJSObjectRef(arg)); +} + +Api::Messaging::MessageType ConverterMessage::toMessageType(JSObjectRef arg) +{ + // convert JSvalue to message type enum + std::string strMsgType = toString(arg); + LogDebug("Messasge Type : " << strMsgType); + + if ( strMsgType.compare("SMS") == 0 ) + { + return Api::Messaging::SMS; + } + else if ( strMsgType.compare("MMS") == 0 ) + { + return Api::Messaging::MMS; + } + else if ( strMsgType.compare("EMAIL") == 0 ) + { + return Api::Messaging::EMAIL; + } + else if ( strMsgType.compare("CHAT") == 0 ) + { + return Api::Messaging::CHAT; + } + else + { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "message type not supported"); + } + +} + +std::string ConverterMessage::toMessageType( long msgtype ) +{ + LogDebug("Messasge Type : " << msgtype); + + switch (msgtype) + { + case Api::Messaging::SMS: + return "SMS"; + case Api::Messaging::MMS: + return "MMS"; + case Api::Messaging::EMAIL: + return "EMAIL"; + case Api::Messaging::CHAT: + return "CHAT"; + default : + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "message type not supported"); + } +} + +Api::Messaging::IConversationPtr ConverterMessage::toConversation(const JSValueRef& arg) +{ + return JSConversation::getConversation(m_context, arg); +} + +std::vector ConverterMessage::toVectorOfConversation(const JSValueRef& arg) +{ + std::vector result; + + JSObjectRef jsObject = toJSObjectRef(arg); + + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) + { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result.push_back(toConversation(element)); + } + + return result; + +} +Api::Messaging::AddressType ConverterMessage::toAddressType(JSValueRef arg) +{ + // convert JSvalue to address type enum + string addressType = toString(arg); + if ("destination" == addressType) { + return Api::Messaging::TO_ADDRESS; + } else if ("cc" == addressType) { + return Api::Messaging::CC_ADDRESS; + } else if ("bcc" == addressType) { + return Api::Messaging::BCC_ADDRESS; + } else { + LogError("unknown address type"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } +} + +Api::Messaging::MessagePriority::Priority ConverterMessage::toMessagePriority( + JSValueRef arg) +{ + if (toBool(arg)) { + return Api::Messaging::MessagePriority::HIGH; + } else { + return Api::Messaging::MessagePriority::NORMAL; + } +} + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +Api::Filesystem::INodePtr ConverterMessage::toFilesystemNode(JSValueRef arg) +{ + // TODO It doesn't work even when object IS a JS File, not sure what to do? + // if (!JSValueIsObjectOfClass(m_context, arg, JSFile::getClassRef())) { + // ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Not a JSFile object."); + // } + + JSObjectRef attObj = toJSObjectRef(arg); + JSFile::PrivateObject* privateObject = + static_cast(JSObjectGetPrivate(attObj)); + if (!privateObject) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is NULL."); + } + + Api::Filesystem::INodePtr result = privateObject->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Node object is NULL."); + } + + return result; +} +#endif + +JSValueRef ConverterMessage::toFunctionOrNull(const JSValueRef& arg) +{ + Assert(arg && "Argument is NULL."); + + if (Validator(m_context).isCallback(arg)) { + return arg; + } else if (!JSValueIsNull(m_context, + arg) && !JSValueIsUndefined(m_context, arg)) { + ThrowMsg(ConversionException, "Not a function nor JS null."); + } + return NULL; +} + +JSValueRef ConverterMessage::toFunction(const JSValueRef& arg) +{ + Assert(arg && "Argument is NULL."); + + if (Validator(m_context).isCallback(arg)) { + return arg; + } else if (JSValueIsNull(m_context, + arg) || JSValueIsUndefined(m_context, arg)) { + ThrowMsg(InvalidArgumentException, "JS null passed as function."); + } + ThrowMsg(ConversionException, "Not a function nor JS null."); +} + +MessageSendCallback +ConverterMessage::toMessageSendCallback(const JSValueRef& arg) +{ + JSObjectRef object = toJSObjectRef(arg); + + MessageSendCallback result; + Validator validator(m_context); + + result.onSuccess = JSUtils::getJSPropertyOrUndefined( + m_context, object, SEND_PROPERTY_ONSUCCESS + ); + if (!validator.isNullOrUndefined(result.onSuccess) && + !validator.isCallback(result.onSuccess)) { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Not a valid callback."); + } + + result.onMessageSendSuccess = JSUtils::getJSPropertyOrUndefined( + m_context, object, SEND_PROPERTY_ONMESSAGESENDSUCCESS + ); + if (!validator.isNullOrUndefined(result.onMessageSendSuccess) && + !validator.isCallback(result.onMessageSendSuccess)) { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Not a valid callback."); + } + + result.onMessageSendError = JSUtils::getJSPropertyOrUndefined( + m_context, object, SEND_PROPERTY_ONMESSAGESENDERROR + ); + if (!validator.isNullOrUndefined(result.onMessageSendError) && + !validator.isCallback(result.onMessageSendError)) { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Not a valid callback."); + } + + return result; +} +} +} diff --git a/src/standards/Tizen/Messaging/ConverterMessage.h b/src/standards/Tizen/Messaging/ConverterMessage.h new file mode 100755 index 0000000..f05ab45 --- /dev/null +++ b/src/standards/Tizen/Messaging/ConverterMessage.h @@ -0,0 +1,155 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file + * @author Pawel Misiak (p.misiak@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "MessageSendCallback.h" +#include "MessagingStorageMultiCallback.h" + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +#include +#include +#endif + +#ifndef CONVERTEDMESSAGE_H +#define CONVERTEDMESSAGE_H + +namespace TizenApis { +namespace Tizen1_0 { +class ConverterMessage : public WrtDeviceApis::CommonsJavaScript::Converter +{ + private: + enum messageTypes + { + messageTypeSms = 1, + messageTypeMms = 2, + messageTypeEmail = 3 + }; + + enum messageFolders + { + messageFolderInbox = 1, + messageFolderOutbox = 2, + messageFolderDrafts = 3, + messageFolderSentbox = 4 + }; + static MessageFunctions m_callbackNames[MESSAGING_MULTI_FUNTION_MAX]; + + + public: + using WrtDeviceApis::CommonsJavaScript::Converter::toJSValueRef; + + explicit ConverterMessage(JSContextRef context); + + virtual ~ConverterMessage(); + + OnMessagesChanged toMessageMultifunctions(JSValueRef argument); + + JSContextRef toJSGlobalContext(JSObjectRef arg); + + JSValueRef toJSValueRef(Api::Messaging::FolderType arg); + + JSValueRef toJSValueRef(const std::vector& slides); + + JSValueRef toJSValueRef(Api::Messaging::MessageType arg); + + JSValueRef toJSValueRef(const Api::Messaging::IMessagePtr& arg, + Api::Messaging::EventUpdateMessageAnswerReceiver* listener); + + JSValueRef toJSValueRef(const std::vector& arg, + Api::Messaging::EventUpdateMessageAnswerReceiver* listener); + JSValueRef toJSValueRef(const std::vector& conversations); + JSValueRef toJSValueRef(const std::vector& messagefolders); + + Api::Messaging::IConversationPtr toConversation(const JSValueRef& arg); + std::vector toVectorOfConversation(const JSValueRef& arg); + + JSValueRef toJSValueRef(const Api::Messaging::MessagePriority& arg); + + JSValueRef keyToJSValue(JSValueRef value, + const std::string& key); + + Api::Messaging::IMessagePtr toIMessage(JSValueRef arg); + + Api::Messaging::IMessagePtr toIMessage(JSObjectRef arg); + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + Api::Messaging::IAttachmentPtr toIAttachment(JSValueRef arg); + + Api::Messaging::IAttachmentPtr toIAttachment(JSObjectRef arg); +#endif + + Api::Messaging::Recipients toRecipients(JSValueRef arg); + + std::vector toVectorOfFolderTypes(JSValueRef arg); + + Api::Messaging::FolderType toFolderType(const JSValueRef& arg); + + Api::Messaging::IMessageFolderPtr toIMessageFolder(JSValueRef arg); + + Api::Messaging::IMessageFolderPtr toIMessageFolder(JSObjectRef arg); + + Api::Messaging::MessageType toMessageType(JSValueRef arg); + + Api::Messaging::MessageType toMessageType(JSObjectRef arg); + + std::string toMessageType( long msgtype ); + + Api::Messaging::AddressType toAddressType(JSValueRef arg); + + Api::Messaging::MessagePriority::Priority toMessagePriority(JSValueRef arg); + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + Api::Filesystem::INodePtr toFilesystemNode(JSValueRef arg); +#endif + + + /** + * @throw InvalidArgumentException If not a callback nor JS null. + */ + JSValueRef toFunctionOrNull(const JSValueRef& arg); + + /** + * @throw ConversionException If JS null. + * @throw InvalidArgumentException If not a callback nor JS null. + */ + JSValueRef toFunction(const JSValueRef& arg); + + MessageSendCallback toMessageSendCallback(const JSValueRef& arg); +}; + +typedef WrtDeviceApis::CommonsJavaScript::ConverterFactory ConverterMessageFactory; +} +} + +#endif diff --git a/src/standards/Tizen/Messaging/EventMessagingServicePrivateData.cpp b/src/standards/Tizen/Messaging/EventMessagingServicePrivateData.cpp new file mode 100755 index 0000000..3ecb818 --- /dev/null +++ b/src/standards/Tizen/Messaging/EventMessagingServicePrivateData.cpp @@ -0,0 +1,36 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "EventMessagingServicePrivateData.h" + +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +EventMessagingServicePrivateData::EventMessagingServicePrivateData(const JSCallbackManagerPtr& callbackManager) : + m_callbackManager(callbackManager) +{ +} + +JSCallbackManagerPtr EventMessagingServicePrivateData::getCallbackManager() const +{ + return m_callbackManager; +} + +} +} + diff --git a/src/standards/Tizen/Messaging/EventMessagingServicePrivateData.h b/src/standards/Tizen/Messaging/EventMessagingServicePrivateData.h new file mode 100755 index 0000000..f3ba43d --- /dev/null +++ b/src/standards/Tizen/Messaging/EventMessagingServicePrivateData.h @@ -0,0 +1,68 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef TIZEN_MESSAGING_EVENT_MESSAGING_SERVICE_PRIVATE_H_ +#define TIZEN_MESSAGING_EVENT_MESSAGING_SERVICE_PRIVATE_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +class EventMessagingServicePrivateData : public WrtDeviceApis::Commons::IEventPrivateData +{ + +public: + EventMessagingServicePrivateData(const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr& callbackManager); + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getCallbackManager() const; + + void setMessageJSValueRef(const JSValueRef& msgJSValueRef) + { + m_messageJSValueRef = msgJSValueRef; + } + + JSValueRef getMessageJSValueRef() + { + return m_messageJSValueRef; + } + + void setSyncHandle(int handle) + { + m_sync_handle = handle; + } + + int getSyncHandle() + { + return m_sync_handle; + } + +private: + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_callbackManager; + JSValueRef m_messageJSValueRef; + + int m_sync_handle; + +}; + +typedef DPL::SharedPtr EventMessagingServicePrivateDataPtr; + +} +} +#endif //TIZEN_MESSAGING_EVENT_MESSAGING_SERVICE_PRIVATE_H_ + diff --git a/src/standards/Tizen/Messaging/EventSendMessagePrivateData.cpp b/src/standards/Tizen/Messaging/EventSendMessagePrivateData.cpp new file mode 100755 index 0000000..69d4fba --- /dev/null +++ b/src/standards/Tizen/Messaging/EventSendMessagePrivateData.cpp @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "EventSendMessagePrivateData.h" + +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +EventSendMessagePrivateData::EventSendMessagePrivateData( + const JSCallbackManagerPtr& callbackManager, + const JSCallbackManagerPtr& recipientCallbackManager) : + m_callbackManager(callbackManager), + m_recipientCallbackManager(recipientCallbackManager) +{ +} + +JSCallbackManagerPtr EventSendMessagePrivateData::getCallbackManager() const +{ + return m_callbackManager; +} + +JSCallbackManagerPtr EventSendMessagePrivateData::getRecipientCallbackManager() +const +{ + return m_recipientCallbackManager; +} +} +} diff --git a/src/standards/Tizen/Messaging/EventSendMessagePrivateData.h b/src/standards/Tizen/Messaging/EventSendMessagePrivateData.h new file mode 100755 index 0000000..a83fd54 --- /dev/null +++ b/src/standards/Tizen/Messaging/EventSendMessagePrivateData.h @@ -0,0 +1,44 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef TIZEN_MESSAGING_EVENTSENDMESSAGEPRIVATE_H_ +#define TIZEN_MESSAGING_EVENTSENDMESSAGEPRIVATE_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +class EventSendMessagePrivateData : public WrtDeviceApis::Commons::IEventPrivateData +{ + public: + EventSendMessagePrivateData(const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr& callbackManager, + const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr& recipientCallbackManager); + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getCallbackManager() const; + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getRecipientCallbackManager() const; + + private: + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_callbackManager; + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_recipientCallbackManager; +}; + +typedef DPL::SharedPtr EventSendMessagePrivateDataPtr; +} +} + +#endif diff --git a/src/standards/Tizen/Messaging/JSConversation.cpp b/src/standards/Tizen/Messaging/JSConversation.cpp new file mode 100755 index 0000000..777fd5e --- /dev/null +++ b/src/standards/Tizen/Messaging/JSConversation.cpp @@ -0,0 +1,275 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** +* @file JSConversation.cpp +* @author Kangsoo Lee (wpeter.lee@samsung.com) +* @version 0.1 +*/ + + +#include +#include +#include +#include +#include +#include +#include +#include "JSConversation.h" + + + +using namespace std; +using namespace DPL; +using namespace TizenApis::Api::Messaging; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassDefinition JSConversation::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "Conversation", + NULL, + m_properties, + NULL, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + hasInstance, + NULL +}; + +const char* JSConversation::CONVID = "id"; +const char* JSConversation::TYPE = "type"; +const char* JSConversation::TIMESTAMP = "timestamp"; +const char* JSConversation::MESSAGECOUNT = "messageCount"; +const char* JSConversation::UNREADMESSAGES = "unreadMessages"; +const char* JSConversation::PREVIEW = "preview"; +const char* JSConversation::SUBJECT = "subject"; +const char* JSConversation::READ = "read"; +const char* JSConversation::FROM = "from"; +const char* JSConversation::TO = "to"; +const char* JSConversation::CC = "cc"; +const char* JSConversation::BCC = "bcc"; +const char* JSConversation::LASTMESSAGEID = "lastMessageId"; + +const std::string JSConversation::TYPE_SMS = "SMS"; +const std::string JSConversation::TYPE_MMS = "MMS"; +const std::string JSConversation::TYPE_EMAIL = "EMAIL"; + +JSStaticValue JSConversation::m_properties[] = { + {"id", JSConversation::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"type", JSConversation::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"timestamp", JSConversation::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"messageCount", JSConversation::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"unreadMessages", JSConversation::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"preview", JSConversation::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"subject", JSConversation::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"read", JSConversation::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"from", JSConversation::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"to", JSConversation::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"cc", JSConversation::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"bcc", JSConversation::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"lastMessageId", JSConversation::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {0, 0, 0, 0} +}; + +const JSClassRef JSConversation::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSConversation::getClassInfo() { + return &m_classInfo; +} + +JSClassRef JSConversation::m_jsClassRef = JSClassCreate(JSConversation::getClassInfo()); + +void JSConversation::initialize(JSContextRef context, JSObjectRef object) +{ + LogDebug("JSConversation::initialize "); + JSConversationPriv* priv = static_cast(JSObjectGetPrivate(object)); +; + if (priv == NULL) + { + LogDebug("Private data is null "); + } + else + { + LogDebug("JSConversation::already exist "); + } +} + + + +JSObjectRef JSConversation::createJSObject(JSContextRef context, IConversationPtr object) +{ + JSConversationPriv* priv = new JSConversationPriv( context, object); + return JSObjectMake(context, getClassRef(), priv); +} + + +void JSConversation::finalize(JSObjectRef object) { + JSConversationPriv* priv = static_cast(JSObjectGetPrivate(object)); + + LogDebug("JSConversation::Finalrize"); + + if (priv != NULL) + { + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +bool JSConversation::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSConversation::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("OK"); + + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + JSConversationPriv* priv = static_cast(JSObjectGetPrivate(object)); + try + { + if (priv == NULL) + { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + IConversationPtr conversation(priv->getObject()); + + if (conversation->getResult() == false) + { + Throw(WrtDeviceApis::Commons::PlatformException); + } + if(JSStringIsEqualToUTF8CString(propertyName, "id")) + { + return converter.toJSValueRef(conversation->getId()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, TYPE)) + { + return converter.toJSValueRef(convertMessageType(conversation->getType())); + } + else if(JSStringIsEqualToUTF8CString(propertyName, TIMESTAMP)) + { + return converter.toJSValueRef(conversation->getTime()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, MESSAGECOUNT)) + { + return converter.toJSValueRef(conversation->getMessageCount()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, UNREADMESSAGES)) + { + return converter.toJSValueRef(conversation->getUnreadMessages()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, PREVIEW)) + { + return converter.toJSValueRef(conversation->getPreview()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, SUBJECT)) + { + return converter.toJSValueRef(conversation->getSubject()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, READ)) + { + return converter.toJSValueRef(conversation->getRead()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, FROM)) + { + return converter.toJSValueRef(conversation->getFrom()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, TO)) + { + return converter.toJSValueRef(conversation->getTo()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, CC)) + { + return converter.toJSValueRef(conversation->getCC()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, BCC)) + { + return converter.toJSValueRef(conversation->getBCC()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, LASTMESSAGEID)) + { + return converter.toJSValueRef(conversation->getLastMessageId()); + } + + } + catch (const WrtDeviceApis::Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + } + return JSValueMakeNull(context); +} + +bool JSConversation::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +IConversationPtr JSConversation::getConversation(JSContextRef context, JSValueRef value) +{ + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) + { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSConversationPriv *priv = static_cast(JSObjectGetPrivate(object)); + + if (!priv) + { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +std::string JSConversation::convertMessageType(int msgType){ + + if(msgType == Api::Messaging::SMS){ + return JSConversation::TYPE_SMS; + }else if(msgType == Api::Messaging::MMS){ + return JSConversation::TYPE_MMS; + }else if(msgType == Api::Messaging::EMAIL){ + return JSConversation::TYPE_EMAIL; + }else{ + return NULL; + } + } + +} +}// WrtPlugins + + diff --git a/src/standards/Tizen/Messaging/JSConversation.h b/src/standards/Tizen/Messaging/JSConversation.h new file mode 100755 index 0000000..0776826 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSConversation.h @@ -0,0 +1,120 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @file JSConversation.h + * @author Kangsoo Lee (wpeter.lee@samsung.com) + * @version 0.1 + * @brief Declaration of the Templete class + */ + +#ifndef WRTPLUGINS_TIZEN_JS_CONVERSATION_H_ +#define WRTPLUGINS_TIZEN_JS_CONVERSATION_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSConversationPriv; + +class JSConversation { +public: +//@struct JSClassDefinition +// @abstract This structure contains properties and callbacks that define a type of object. All fields other than the version field are optional. Any pointer may be NULL. + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, Api::Messaging::IConversationPtr object); + static Api::Messaging::IConversationPtr getConversation(JSContextRef context, JSValueRef value); + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + static std::string convertMessageType(int msgType); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + + /** + * The callback invoked when determining whether an object has a property. + */ + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + /** + * The callback invoked when getting a property's value. + */ + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticValue m_properties[]; + static JSClassRef m_jsClassRef; + + + + static const char* CONVID; + static const char* TYPE; + static const char* TIMESTAMP; + static const char* MESSAGECOUNT; + static const char* UNREADMESSAGES; + static const char* PREVIEW; + static const char* SUBJECT; + static const char* READ; + static const char* FROM; + static const char* TO; + static const char* CC; + static const char* BCC; + static const char* LASTMESSAGEID; + + static const std::string TYPE_SMS; + static const std::string TYPE_MMS; + static const std::string TYPE_EMAIL; + +}; + +} +} //WrtPlugins + +#endif //WRTPLUGINS_TIZEN_JS_MESSAGING_SERVICE_MANAGER_H_ + + diff --git a/src/standards/Tizen/Messaging/JSMessage.cpp b/src/standards/Tizen/Messaging/JSMessage.cpp new file mode 100755 index 0000000..46b4063 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessage.cpp @@ -0,0 +1,1505 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file JSMessage.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ + +#define PLUGIN_CONFIG_BLOCKING // milkelf.choi, 2011 10 10 - temporary : + +#include +#include +#include +#include +#include +#include +#include "ConverterMessage.h" +#include "JSMessage.h" +#include "JSRecipientArray.h" +#include "JSMessagePrivateObject.h" +#include "JSMessagingListener.h" +#include + +#include +#include +#include + +#include "MessagingErrorMsg.h" +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +#include "JSMessageAttachment.h" +#endif + +#ifndef PLUGIN_CONFIG_BLOCKING +#include "plugin_config.h" +#endif +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +// filesystem +#include +#endif +using namespace std; +using namespace TizenApis::Api::Messaging; +using namespace TizenApis::Commons; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { +JSClassRef JSMessage::m_jsClassRef = NULL; + +JSClassDefinition JSMessage::m_classInfo = { + 0, + kJSClassAttributeNone, + "MessagingMessage", + 0, + m_property, + NULL, //m_function + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +// JSMessage properties +JSStaticValue JSMessage::m_property[] = { +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + { "attachments", getAttachments, setAttachments, kJSPropertyAttributeNone }, +#endif + { "bcc", getBccAddress, setBccAddress, kJSPropertyAttributeNone }, + { "accountId", getAccountID, NULL, kJSPropertyAttributeReadOnly}, +// { "uid", getUID, NULL, kJSPropertyAttributeReadOnly}, + { "messageStatus", getMessageStatus, NULL, kJSPropertyAttributeReadOnly}, + { "body", getMessageBody, setMessageBody, kJSPropertyAttributeNone }, + + { "cc", getCcAddress, setCcAddress, kJSPropertyAttributeNone }, + { "to", getDestinationAddress, setDestinationAddress, kJSPropertyAttributeNone }, + { "isRead", getIsRead, setIsRead, kJSPropertyAttributeNone }, + { "id", getMessageId, NULL, kJSPropertyAttributeReadOnly }, + { "priority", getMessagePriority, setMessagePriority, kJSPropertyAttributeNone }, + { "type", getMessageType, NULL, kJSPropertyAttributeReadOnly }, + { "from", getSourceAddress, NULL, kJSPropertyAttributeReadOnly }, + { "subject", getSubject, setSubject, kJSPropertyAttributeNone }, + { "timestamp", getTime, NULL, kJSPropertyAttributeReadOnly }, + { "folderId", getFolder, NULL, kJSPropertyAttributeReadOnly }, + { "conversationId", getConversationId, NULL, kJSPropertyAttributeReadOnly }, + { "inResponseTo", getInResponseTo, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSValueRef JSMessage::createJSObject(JSContextRef context, + Api::Messaging::EmailAccountInfo& account, + Api::Messaging::MessageType msgType, + const std::string& msgId) +{ + Api::Messaging::IMessagePtr msg; + LogDebug("createJSObject with account "); + + Try + { + if (msgType == Api::Messaging::EMAIL) { + LogDebug("Account Address:" << &account); + LogDebug("Account Data ,ID" << account.getId() << "name:" << account.getName() << " Account:" << account.getAddress()); + + msg = Api::Messaging::MessageFactory::createMessage(msgType, account, msgId); + if (!msg) + return JSValueMakeUndefined(context); + } else { + Throw(WrtDeviceApis::Commons::UnknownException); // unsupported type + } + } + Catch(WrtDeviceApis::Commons::UnknownException) { + LogError("wrong message type, object not created"); + return JSValueMakeUndefined(context); + } + + return createJSObject(context, msg); +} + +JSValueRef JSMessage::createJSObject(JSContextRef context, + Api::Messaging::EventUpdateMessageAnswerReceiver* listener, + Api::Messaging::MessageType msgType, + const string& msgId) +{ + Api::Messaging::IMessagePtr msg; + Try + { + // create message depending on type + if (msgType == Api::Messaging::SMS || msgType == Api::Messaging::MMS || msgType == Api::Messaging::EMAIL) { + msg = Api::Messaging::MessageFactory::createMessage(msgType, msgId); + if (!msg) + return JSValueMakeUndefined(context); + } else { + Throw(WrtDeviceApis::Commons::UnknownException); // unsupported type + } + } + Catch(WrtDeviceApis::Commons::UnknownException) { + LogError("wrong message type, object not created"); + return JSValueMakeUndefined(context); + } + return createJSObject(context, msg, listener); +} + +JSValueRef JSMessage::createJSObject(JSContextRef context, + const Api::Messaging::IMessagePtr& msg, + Api::Messaging::EventUpdateMessageAnswerReceiver* listener) +{ + JSClassRef jsClassRef = JSClassCreate(getClassInfo()); + JSMessagePrivateObject* priv = new JSMessagePrivateObject(context, msg); + priv->setUpdateMsgReceiver(listener); + JSObjectRef jsValueRef = + JSObjectMake(context, jsClassRef, static_cast(priv)); + JSClassRelease(jsClassRef); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +JSValueRef JSMessage::createJSObject(JSContextRef context, + const Api::Messaging::IMessagePtr& msg) +{ + LogDebug("createJSObject"); + JSClassRef jsClassRef = JSClassCreate(getClassInfo()); + LogDebug("jsClassRef success"); + JSMessagePrivateObject* priv = new JSMessagePrivateObject(context, msg); + LogDebug("priv success"); + + JSObjectRef jsValueRef = JSObjectMake(context, jsClassRef, static_cast(priv)); + LogDebug("JSObjectMake success"); + JSClassRelease(jsClassRef); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + +JSValueRef JSMessage::createJSObject(JSContextRef context, + Api::Messaging::MessageType msgType, + const string& msgId) +{ + Api::Messaging::IMessagePtr msg; + Try + { + // create message depending on type + if (msgType == Api::Messaging::SMS || msgType == Api::Messaging::MMS || msgType == Api::Messaging::EMAIL) { + msg = Api::Messaging::MessageFactory::createMessage(msgType, msgId); + } else { + Throw(WrtDeviceApis::Commons::UnknownException); // unsupported type + } + } + Catch(WrtDeviceApis::Commons::UnknownException) { + LogError("wrong message type, object not created"); + return JSValueMakeUndefined(context); + } + return createJSObject(context, msg, NULL); +} + +void JSMessage::initialize(JSContextRef context, + JSObjectRef object) +{ + LogInfo("enter"); + JSMessagePrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + LogDebug("priv=" << priv); + if (!priv) { + LogWarning("empty jsObject creation"); + } +} + +void JSMessage::finalize(JSObjectRef object) +{ + JSMessagePrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + if (priv) { + LogDebug("deleting private object"); + delete priv; + JSObjectSetPrivate(object, NULL); + } +} + +bool JSMessage::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + return false; +} + +JSValueRef JSMessage::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogError("should not enter"); + return JSValueMakeUndefined(context); +} + +bool JSMessage::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogError("should not enter"); + return false; +} + +bool JSMessage::deleteProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogInfo("enter"); + return true; +} + +void JSMessage::getPropertyNames(JSContextRef context, + JSObjectRef object, + JSPropertyNameAccumulatorRef propertyNames) +{ + LogInfo("enter"); +} + +JSValueRef JSMessage::callAsFunction(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogInfo("enter"); + return JSValueMakeUndefined(context); +} + +bool JSMessage::hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception) +{ + LogInfo("enter"); + return true; +} + +JSValueRef JSMessage::convertToType(JSContextRef context, + JSObjectRef object, + JSType type, + JSValueRef* exception) +{ + LogInfo("enter"); + return JSValueMakeUndefined(context); +} + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +JSValueRef JSMessage::getAttachments(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogInfo("enter"); + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::MessageType msgType = msg->getMessageType(); + + // prepare common values + JSCallbackManagerPtr emptyCallbackMgr = JSCallbackManager::createObject( + converter->toJSGlobalContext(object), + NULL, + NULL); + + switch (msgType) { + case Api::Messaging::MMS: + case Api::Messaging::EMAIL: + { + + std::vector attachments; + std::vector::iterator it; + + if (msgType == Api::Messaging::MMS ) + { + Api::Messaging::AttachmentsPtr mmsAttachments = + DPL::StaticPointerCast(Api::Messaging::MessageFactory::convertToEmail(msg)); + attachments = mmsAttachments->getAttachments(); + } + else + { + Api::Messaging::AttachmentsPtr emailAttachments = + DPL::StaticPointerCast(Api::Messaging::MessageFactory::convertToEmail(msg)); + attachments = emailAttachments->getAttachments(); + } + + int count = attachments.size(); + LogDebug( "count : " << count); + + JSObjectRef jsMessageAttachmentObject[count]; //make + + for (int index = 0 ; index < attachments.size(); index++ ) + { + LogDebug( "Attachment ID : " << attachments[index]->getAttachmentID()); + jsMessageAttachmentObject[index] = JSMessageAttachment::createJS(context, attachments[index] ); + } + JSObjectRef result = JSObjectMakeArray(context, count, jsMessageAttachmentObject, NULL); + + return result; + + } + case Api::Messaging::SMS: + return JSValueMakeUndefined(context); // ignore + + default: + LogError("not supported message type"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + return JSValueMakeUndefined(context); +} +#endif + +JSValueRef JSMessage::getBccAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::MessageType msgType = msg->getMessageType(); + + switch (msgType) { + case Api::Messaging::EMAIL: + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + Api::Messaging::RecipientsPtr recipient = email->getBccRecipientsPtr(); + return JSRecipientArray::createArray(converter->toJSGlobalContext( + object), recipient); + } + case Api::Messaging::SMS: + case Api::Messaging::MMS: + return JSValueMakeUndefined(context); // ignore + + default: + LogError("not supported message type"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); // unsupported type + break; + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + string body = msg->getBody(); + return converter->toJSValueRef(body); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getCcAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::MessageType msgType = msg->getMessageType(); + + switch (msgType) { + case Api::Messaging::EMAIL: + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + Api::Messaging::RecipientsPtr recipient = email->getCcRecipientsPtr(); + return JSRecipientArray::createArray(converter->toJSGlobalContext( + object), recipient); + } + case Api::Messaging::MMS: + case Api::Messaging::SMS: + return JSValueMakeUndefined(context); // ignore + + default: + LogError("not supported message type"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); // unsupported type + + break; + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getDestinationAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogInfo("enter"); + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::RecipientsPtr recipient = msg->getToRecipientsPtr(); + return JSRecipientArray::createArray(converter->toJSGlobalContext( + object), recipient); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getIsRead(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + bool isRead = msg->isRead(); + return converter->toJSValueRef(isRead); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getMessageId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + const string& id = msg->getIdRef(); + LogDebug("msgId=" << id); + return converter->toJSValueRef(id); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getMessagePriority(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::MessageType msgType = msg->getMessageType(); + + switch (msgType) { + case Api::Messaging::SMS: + case Api::Messaging::MMS: + return JSValueMakeUndefined(context); + + case Api::Messaging::EMAIL: + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + return converter->toJSValueRef(static_cast(* + email)); + } + + default: + LogError("unsupported message type"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); // unsupported type + break; + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getMessageType(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::MessageType msgType = msg->getMessageType(); + + return converter->toJSValueRef(converter->toMessageType(msgType)); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getSourceAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + + //This property is set up by the device or the web runtime environment. + //This property should only be taken into account for Email. + // TODO Verify with Tizen. + // if (msg->getMessageType() != Api::Messaging::EMAIL && msg->getMessageType() != Api::VIRTUAL_MESSAGE) { + // return JSValueMakeUndefined(context); + // } + return converter->toJSValueRef(msg->getSourceAddress()); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getSubject(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::MessageType msgType = msg->getMessageType(); + + switch (msgType) { + case Api::Messaging::MMS: + { + Api::Messaging::IMmsPtr mms = Api::Messaging::MessageFactory::convertToMms(msg); + return converter->toJSValueRef(mms->getSubject()); + } + case Api::Messaging::EMAIL: + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + return converter->toJSValueRef(email->getSubject()); + } + case Api::Messaging::SMS: + return JSValueMakeUndefined(context); // ignore + default: + LogError("message not support subject"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); // unsupported type + break; + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::UnsupportedException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getTime(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + struct tm dateTime = msg->getDateTime(); + return converter->toJSValueRef(dateTime); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getFolder(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::FolderType folder = msg->getCurrentFolder(); + return converter->toJSValueRef(folder); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getMessageBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogInfo("getMessageBody"); + + Try + { + JSMessagePrivateObject* priv = static_cast(JSObjectGetPrivate(object)); + Assert(priv && "Private object is NULL."); + + JSContextRef globalContext = priv->getContext(); + + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(globalContext); + + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); //get message point + LogInfo("create JS"); + + return JSMessageBody::createJS(globalContext, msg); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getAccountID(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogInfo("getAccountID"); + + Try + { + JSMessagePrivateObject* priv = static_cast(JSObjectGetPrivate(object)); + Assert(priv && "Private object is NULL."); + + JSContextRef globalContext = priv->getContext(); + + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(globalContext); + + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); //get message point + + LogInfo("create JS"); + //getAccountID + if (msg->getMessageType() == Api::Messaging::EMAIL) + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + + std::stringstream stream; + stream << email->getAccountID(); + if (stream.fail()) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Couldn't convert e-mail account id"); + } + + return converter->toJSValueRef(stream.str()); + } + else + { + return JSValueMakeUndefined(context); + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getUID(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) + { + LogInfo("getUID"); + + Try + { + JSMessagePrivateObject* priv = static_cast(JSObjectGetPrivate(object)); + Assert(priv && "Private object is NULL."); + + JSContextRef globalContext = priv->getContext(); + + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(globalContext); + + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); //get message point + + LogInfo("create JS"); + //getAccountID + if (msg->getMessageType() == Api::Messaging::EMAIL) + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + return converter->toJSValueRef(email->getUID()); + } + else + { + return JSValueMakeUndefined(context); + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + return JSValueMakeUndefined(context); + } + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +bool JSMessage::setAttachments(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogInfo("enter"); + + Try + { + JSMessagePrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + + if (!priv) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + vector attachments; + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + if (JSIsArrayValue(context, value)) { + JSObjectRef valueObj = converter->toJSObjectRef(value); + + // extract path from each JSFile object + unsigned int len = JSGetArrayLength(context, valueObj); + for (unsigned int i = 0; i < len; ++i) { + JSValueRef att = JSGetArrayElement(context, valueObj, i); + if (JSValueIsUndefined(context, + att) || JSValueIsNull(context, att)) { + LogWarning("Invalid array element. Skipping."); + continue; + } + Api::Filesystem::INodePtr node = converter->toFilesystemNode( + att); + + LogDebug("Adding attachment: " << node->getPath()->getFullPath()); + attachments.push_back(node->getPath()->getFullPath()); + } + } else { + LogWarning("Invalid or null element passed as attachment array." << + "Setting empty vector."); + } + + // set up new attachments list + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::MessageType msgType = msg->getMessageType(); + switch (msgType) { + case Api::Messaging::MMS: + { + Api::Messaging::IMmsPtr mms = Api::Messaging::MessageFactory::convertToMms(msg); + mms->setAttachments(attachments, true); + break; + } + case Api::Messaging::EMAIL: + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + email->setAttachments(attachments, true); + break; + } + case Api::Messaging::SMS: + + return false; // ignore + + default: + LogError("not supported message type"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + return true; + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + LogError("Invalid argument"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + return false; +} +#endif + +bool JSMessage::setBccAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::Recipients bcc = converter->toRecipients(value); + LogDebug("setting bcc field, size=" << bcc.getRecipientSize()); + + Api::Messaging::MessageType msgType = msg->getMessageType(); + switch (msgType) { + case Api::Messaging::SMS: + case Api::Messaging::MMS: + return false; // ignore + + case Api::Messaging::EMAIL: + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + email->setBccRecipients(bcc); + break; + } + default: + LogError("unsupported message type"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); // unsupported type + } + return true; + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Platform execution"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return false; +} + +bool JSMessage::setBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + string body = converter->toString(value); + msg->setBody(body); + return true; + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Platform execution"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + return false; +} + +bool JSMessage::setCcAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::Recipients cc = converter->toRecipients(value); + LogDebug("setting cc field, size=" << cc.getRecipientSize()); + + Api::Messaging::MessageType msgType = msg->getMessageType(); + switch (msgType) { + case Api::Messaging::SMS: + case Api::Messaging::MMS: + return false; // ignore + + case Api::Messaging::EMAIL: + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + email->setCcRecipients(cc); + break; + } + default: + LogError("unsuported message type"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); // unsupported type + break; + } + return true; + } + + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Platform execution"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return false; +} + +bool JSMessage::setDestinationAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef * exception) +{ + LogInfo("enter"); + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::Recipients to = converter->toRecipients(value); + LogDebug("setting to field, size=" << to.getRecipientSize()); + msg->setToRecipients(to); + return true; + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Platform execution"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return false; +} + +bool JSMessage::setIsRead(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef * exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + msg->setReadStatus(converter->toBool(value)); + msg->setisReadChangeStatus(converter->toBool(value)); + return true; + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return false; +} + +bool JSMessage::setMessagePriority(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef * exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::MessageType msgType = msg->getMessageType(); + switch (msgType) { + case Api::Messaging::MMS: + case Api::Messaging::SMS: + return false; // ignore + + case Api::Messaging::EMAIL: + msg->setPriority(converter->toMessagePriority(value)); + break; + + default: + LogError("unsuported message type"); + Throw(WrtDeviceApis::Commons::ConversionException); + break; + } + return true; + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Platform execution"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return false; +} + +bool JSMessage::setSubject(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef * exception) +{ + Try + { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::MessageType msgType = msg->getMessageType(); + string subject = converter->toString(value); + switch (msgType) { + case Api::Messaging::MMS: + { + Api::Messaging::IMmsPtr mms = Api::Messaging::MessageFactory::convertToMms(msg); + mms->setSubject(subject); + break; + } + case Api::Messaging::EMAIL: + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + email->setSubject(subject); + break; + } + case Api::Messaging::SMS: + return false; // ignore + + default: + LogError("message not supported"); + Throw(WrtDeviceApis::Commons::UnsupportedException); + break; + } + return true; + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Platform execution"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::UnsupportedException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); + } + + return false; +} + +bool JSMessage::setMessageBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + LogDebug("Set Message Body. ????"); + return true; + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Platform execution"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return false; +} + +JSValueRef JSMessage::getConversationId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("OK"); + + Try + { + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context); + int convId = 0; + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + Api::Messaging::EventGetConversationIdPtr event(new Api::Messaging::EventGetConversationId()); + event->setConversationMsgPtr(msg); + event->setForSynchronousCall(); + Api::Messaging::ReqReceiverMessageSingleton::Instance().getConversationId(event); + + convId = event->getConversationId(); + + return converter->toJSValueRef(convId); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Platform execution"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessage::getInResponseTo(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("OK"); + + Try + { + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context); + int convId = 0; + int msgId = 0; + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); + if (msg->getMessageType() == EMAIL) + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + msgId = email->getUID(); + + Api::Messaging::EventGetConversationIdPtr event(new Api::Messaging::EventGetConversationId()); + event->setConversationMsgPtr(msg); + event->setForSynchronousCall(); + Api::Messaging::ReqReceiverMessageSingleton::Instance().getConversationId(event); + convId = event->getConversationId(); + + if (convId == msgId) + convId = -1; // error case, original message + } + else + { + convId = -1; + } + + return converter->toJSValueRef(convId); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Platform execution"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + + return JSValueMakeUndefined(context); +} + + +JSValueRef JSMessage::getMessageStatus(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogInfo("getMessageStatus"); + + Try + { + JSMessagePrivateObject* priv = static_cast(JSObjectGetPrivate(object)); + Assert(priv && "Private object is NULL."); + + JSContextRef globalContext = priv->getContext(); + + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(globalContext); + + Api::Messaging::IMessagePtr msg = converter->toIMessage(object); //get message point + + LogInfo("create JS"); + return converter->toJSValueRef(msg->getMessageStatus()); + + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeUndefined(context); +} + + +} +} diff --git a/src/standards/Tizen/Messaging/JSMessage.h b/src/standards/Tizen/Messaging/JSMessage.h new file mode 100755 index 0000000..014cd12 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessage.h @@ -0,0 +1,325 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file JSMessage.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef JSMESSAGE_H +#define JSMESSAGE_H + +#include +#include +#include +#include +#include +#include +#include "JSMessageBody.h" + +namespace TizenApis { +namespace Tizen1_0 { +class JSMessage +{ + static JSClassRef m_jsClassRef; + + public: + + /* + * This method initializes object in the JS Engine. + */ + static JSClassRef jsInit(JSContextRef context) + { + LogInfo("enter"); + return JSClassCreate(&m_classInfo); + } + + static const JSClassDefinition* getClassInfo() + { + LogInfo("enter"); + return &(m_classInfo); + } + + static JSClassRef getClassRef() + { + LogInfo("enter"); + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; + } + + static JSValueRef createJSObject(JSContextRef context, + Api::Messaging::EmailAccountInfo& account, + Api::Messaging::MessageType msgType, + const std::string& msgId = ""); + + static JSValueRef createJSObject(JSContextRef context, + Api::Messaging::EventUpdateMessageAnswerReceiver* listener, + Api::Messaging::MessageType msgType = Api::Messaging::MESSAGETYPE_COUNT, + const std::string& msgId = ""); + + static JSValueRef createJSObject(JSContextRef context, + Api::Messaging::MessageType msgType = Api::Messaging::MESSAGETYPE_COUNT, + const std::string& msgId = ""); + + static JSValueRef createJSObject(JSContextRef context, + const Api::Messaging::IMessagePtr& msg, + Api::Messaging::EventUpdateMessageAnswerReceiver* listener); + + static JSValueRef createJSObject(JSContextRef context, + const Api::Messaging::IMessagePtr& msg); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when determining whether an object has a property. + */ + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * The callback invoked when setting a property's value. + */ + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + /** + * The callback invoked when deleting a property. + */ + static bool deleteProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * The callback invoked when collecting the names of an object's properties. + */ + static void getPropertyNames(JSContextRef context, + JSObjectRef object, + JSPropertyNameAccumulatorRef propertyNames); + + /** + * The callback invoked when an object is called as a function. + */ + static JSValueRef callAsFunction(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception); + + /** + * The callback invoked when converting an object to a particular JavaScript type. + */ + static JSValueRef convertToType(JSContextRef context, + JSObjectRef object, + JSType type, + JSValueRef* exception); +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + static JSValueRef getAttachments(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); +#endif + static JSValueRef getBccAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getCallbackNumber(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getCcAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getDestinationAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getIsRead(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getMessageId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getMessagePriority(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getMessageType(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getSourceAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getSubject(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getTime(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getFolder(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getMessageBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getAccountID(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getUID(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + static bool setAttachments(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +#endif + static bool setBccAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static bool setBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static bool setCcAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static bool setDestinationAddress(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static bool setIsRead(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static bool setMessagePriority(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static bool setSubject(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + static bool setMessageBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef update(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef getConversationId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getInResponseTo(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + + static JSValueRef getMessageStatus(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; +} +} + +#endif diff --git a/src/standards/Tizen/Messaging/JSMessageAttachment.cpp b/src/standards/Tizen/Messaging/JSMessageAttachment.cpp new file mode 100755 index 0000000..7a24fa0 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessageAttachment.cpp @@ -0,0 +1,345 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @file JSAttachmentArray.cpp + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 0.1 + */ + +#include +#include +#include +#include "ConverterMessage.h" +#include "JSMessageAttachment.h" +#include "JSAttachmentArray.h" //attachment array +#include +#include +#include +#include +#include + +#include "MessagingErrorMsg.h" + +namespace { +const char* MSG_ATTACHMENT_MIMETYPE = "MIMEType"; +const char* MSG_ATTACHMENT_MESSAGEID = "messageId"; +const char* MSG_ATTACHMENT_CONTENTLOCATION = "contentLocation"; +const char* MSG_ATTACHMENT_CONTENTID = "contentId"; +const char* MSG_ATTACHMENT_LOADED = "loaded"; +} + +namespace TizenApis { +namespace Tizen1_0 { + +using namespace TizenApis::Commons; +using namespace TizenApis::Api::Messaging; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +JSClassRef JSMessageAttachment::m_jsClassRef = NULL; + +JSClassDefinition JSMessageAttachment::m_classInfo = { + 0, + kJSClassAttributeNone, + "MessageAttachment", + /*NULL,*/ + /*JSFile::getClassRef(), parent*/ + NULL, + m_property, + NULL, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getproperty + NULL, //setProperty + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSMessageAttachment::m_property[] = { + //{ "MIMEType", JSMessageAttachment::getMIMEType, NULL, kJSPropertyAttributeReadOnly }, + { "messageId", JSMessageAttachment::getMessageID, NULL, kJSPropertyAttributeReadOnly }, + //{ "contentLocation", JSMessageAttachment::getContentLocation, NULL, kJSPropertyAttributeNone }, + { "contentId", JSMessageAttachment::getContentID, NULL, kJSPropertyAttributeNone }, + { "loaded", JSMessageAttachment::getLoaded, NULL, kJSPropertyAttributeReadOnly }, + { "file", JSMessageAttachment::getFile, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; +const JSClassDefinition* JSMessageAttachment::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSMessageAttachment::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +void JSMessageAttachment::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("enter"); +} + +void JSMessageAttachment::finalize(JSObjectRef object) +{ + LogDebug("enter"); + JSMessageAttachmentPrivate* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + +JSObjectRef JSMessageAttachment::createJS( JSContextRef context, const Api::Messaging::IAttachmentPtr& attachment) +{ + + JSMessageAttachmentPrivate *priv = new JSMessageAttachmentPrivate(context, attachment); + return JSObjectMake(context, getClassRef(), priv); //make JSObjectRef. +} + +JSValueRef JSMessageAttachment::getMIMEType(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + Try + { + Api::Messaging::IAttachmentPtr attachment = getAttachment(context, object); + + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + LogDebug("mine type :" << attachment->getMimeType()); + return converter.toJSValueRef(attachment->getMimeType()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessageAttachment::getMessageID(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + Try + { + Api::Messaging::IAttachmentPtr attachment = getAttachment(context, object); + + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + LogDebug("Message ID :" << (attachment->getMessage())); + return converter.toJSValueRef(attachment->getMessage()->getId()); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("invalid value conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("Unkown Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSMessageAttachment::getContentLocation(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + return JSValueMakeNull(context); +} + +JSValueRef JSMessageAttachment::getContentID(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + Try + { + Api::Messaging::IAttachmentPtr attachment = getAttachment(context, object); + + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + LogDebug("Attachment Loaded :" << (attachment->getDownloaded() )); + return converter.toJSValueRef(attachment->getAttachmentID()); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("invalid value conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("Unkown Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeUndefined(context); + +} + +JSValueRef JSMessageAttachment::getLoaded(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + + LogDebug("enter"); + Try + { + Api::Messaging::IAttachmentPtr attachment = getAttachment(context, object); + + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + LogDebug("Attachment Loaded :" << (attachment->getDownloaded() )); + return converter.toJSValueRef(attachment->getDownloaded()); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("invalid value conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("Unkown Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessageAttachment::getFile(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + Try + { + Api::Messaging::IAttachmentPtr attachment = getAttachment(context, object); + if (!attachment) { + return JSValueMakeUndefined(context); + } + + std::string fullPath = attachment->getFullPath(); + LogDebug("full Path = " << fullPath ); + if (fullPath.empty()) { + return JSValueMakeUndefined(context); + } + + int permissions = Api::Filesystem::PERM_READ | Api::Filesystem::PERM_WRITE; + EventGetNodeDataPtr data( + new EventGetNodeData(permissions, WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr()) + ); + Api::Filesystem::EventResolvePtr event(new Api::Filesystem::EventResolve( + Api::Filesystem::IPath::create(fullPath)) + ); + event->setPrivateData( + DPL::StaticPointerCast(data) + ); + event->setForSynchronousCall(); + Api::Filesystem::IManager::getInstance().getNode(event); + + WrtDeviceApis::Commons::ExceptionCodes::Enumeration code = event->getExceptionCode(); + if (code != WrtDeviceApis::Commons::ExceptionCodes::None) { + LogError("Attachment location not resolved. Exception code: " << code); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + + } + + Api::Filesystem::INodePtr node = event->getResult(); + if (!node) { + LogError("Resolved attachment location is empty."); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + + } + + Api::Filesystem::IPathPtr path = node->getPath(); + + LogError(" Path = " << path->getPath() << " Full Path = " << path->getFullPath()); + + JSObjectRef result = WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(context, + JSFile::getClassRef(), + node); + return result; + + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("invalid value conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("Unkown Exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + return JSValueMakeUndefined(context); + +} + +Api::Messaging::IAttachmentPtr JSMessageAttachment::getAttachment(JSContextRef context, + JSValueRef value) +{ + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + return getAttachment(context, converter.toJSObjectRef(value)); +} + +Api::Messaging::IAttachmentPtr JSMessageAttachment::getAttachment(JSContextRef context, + JSObjectRef object) +{ + // private object of thisObject + return getPrivate(object)->getObject(); +} + +JSMessageAttachmentPrivate* JSMessageAttachment::getPrivate(JSObjectRef thisObject) +{ + JSMessageAttachmentPrivate* thisPrivate = + static_cast(JSObjectGetPrivate(thisObject)); + if (!thisPrivate) { + LogError("no private"); + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return thisPrivate; +} + +} +} + + diff --git a/src/standards/Tizen/Messaging/JSMessageAttachment.h b/src/standards/Tizen/Messaging/JSMessageAttachment.h new file mode 100755 index 0000000..42cca02 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessageAttachment.h @@ -0,0 +1,144 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file JSMessage.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGINS_TIZEN_JS_MESSAGE_ATTACHMENT_H_ +#define WRT_PLUGINS_TIZEN_JS_MESSAGE_ATTACHMENT_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSMessageAttachmentPrivate; //IAttachmentPtr + +class JSMessageAttachment +{ + static JSClassRef m_jsClassRef; + +public: + static const JSClassDefinition* getClassInfo(); + static JSClassRef getClassRef(); + static JSObjectRef createJS( JSContextRef context, const Api::Messaging::IAttachmentPtr &msg); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + + /** + * Get MIME Type of Attachment File. readonly + */ + static JSValueRef getMIMEType(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + + static JSValueRef getMessageID(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getContentLocation(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getContentID(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + + static JSValueRef getLoaded(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getFile(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /* + * returns private object or throws WrtDeviceApis::Commons::NullPointerException + */ + static JSMessageAttachmentPrivate* getPrivate(JSObjectRef value); + + /* + * extracts Api Message representation + * throws WrtDeviceApis::Commons::NullPointerException if there's no private object + * throws WrtDeviceApis::Commons::ConversionException if it's not possible to convert to JSObjectRef + */ + static Api::Messaging::IAttachmentPtr getAttachment(JSContextRef context, + JSValueRef value); + + /* + * extracts Api Message representation + * throws WrtDeviceApis::Commons::NullPointerException if there's no private object + */ + static Api::Messaging::IAttachmentPtr getAttachment(JSContextRef context, + JSObjectRef object); + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + +}; + +} +} + +#endif //WRT_PLUGINS_TIZEN_JS_MESSAGE_ATTACHMENT_H_ + diff --git a/src/standards/Tizen/Messaging/JSMessageBody.cpp b/src/standards/Tizen/Messaging/JSMessageBody.cpp new file mode 100755 index 0000000..54ba0a6 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessageBody.cpp @@ -0,0 +1,370 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @file JSAttachmentArray.cpp + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 0.1 + */ + +#include +#include +#include +#include "ConverterMessage.h" +#include "JSMessageBody.h" +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +#include "JSAttachmentArray.h" +#endif +#include +#include +#include "MessagingErrorMsg.h" + +namespace TizenApis { +namespace Tizen1_0 { + + using namespace TizenApis::Commons; + using namespace TizenApis::Api::Messaging; + using namespace WrtDeviceApis::Commons; + using namespace WrtDeviceApis::CommonsJavaScript; + + +JSClassRef JSMessageBody::m_jsClassRef = NULL; + +JSClassDefinition JSMessageBody::m_classInfo = { + 0, + kJSClassAttributeNone, + "MessagingMessageBody", + 0, + m_property, + NULL, + initialize, + finalize, + hasProperty, + NULL, //getproperty + NULL, //setProperty + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSMessageBody::m_property[] = { + { "messageId", JSMessageBody::getMessageID, NULL, kJSPropertyAttributeReadOnly }, + { "loaded", JSMessageBody::getLoadedStatus, NULL, kJSPropertyAttributeReadOnly }, + { "plainBody", JSMessageBody::getPlainBody, JSMessageBody::setPlainBody, kJSPropertyAttributeNone }, + { "htmlBody", JSMessageBody::getHtmlBody, JSMessageBody::setHtmlBody, kJSPropertyAttributeNone }, +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + { "inlineAttachments", NULL, NULL, kJSPropertyAttributeReadOnly }, +#endif + { 0, 0, 0, 0 } +}; + +const JSClassDefinition* JSMessageBody::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSMessageBody::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +bool JSMessageBody::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Try + { + Api::Messaging::IMessagePtr msg = getMessage(context, object); + + if (!msg) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +void JSMessageBody::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("enter"); +} + +void JSMessageBody::finalize(JSObjectRef object) +{ + LogDebug("enter"); + JSMessageBodyPrivate* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + +JSObjectRef JSMessageBody::createJS( JSContextRef context, const Api::Messaging::IMessagePtr &msg) +{ + JSMessageBodyPrivate *priv = new JSMessageBodyPrivate(context, msg); + return JSObjectMake(context, getClassRef(), priv); //make JSObjectRef. +} + +JSValueRef JSMessageBody::getMessageID(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + Try + { + Api::Messaging::IMessagePtr msg = getMessage(context, object); + + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + return converter.toJSValueRef(msg->getId()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSMessageBody::getLoadedStatus(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + Try + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Api::Messaging::IMessagePtr msg = getMessage(context, object); + + if (msg->getMessageType() == Api::Messaging::EMAIL) + { + //Api::Messaging::IEmailPtr email = DPL::StaticPointerCast(Api::Messaging::MessageFactory::convertToEmail(msg)); + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + return converter.toJSValueRef(email->isBodyDownloaded()); + } + else + { + return converter.toJSValueRef(true); + } + + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSMessageBody::getPlainBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("getPlainBody"); + + Try + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Api::Messaging::IMessagePtr msg = getMessage(context, object); + std::string body = msg->getBody(); + LogDebug("getPlainBody plainBody" << body ); + return converter.toJSValueRef(body); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + + } + return JSValueMakeUndefined(context); +} + +bool JSMessageBody::setPlainBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + + LogDebug("setPlainBody"); + + Try + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Api::Messaging::IMessagePtr msg = getMessage(context, object); + std::string body = converter.toString(value); + msg->setBody(body); + LogDebug("setPlainBody plainBody" << body ); + return true; + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Platform execution"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + return false; +} + +JSValueRef JSMessageBody::getHtmlBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + + LogDebug("getHtmlBody"); + Try + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Api::Messaging::IMessagePtr msg = getMessage(context, object); + + LogDebug("message Type : " << msg->getMessageType() ); + if (msg->getMessageType() == Api::Messaging::EMAIL) + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + + LogDebug("Html Body : " << email->getHtmlBody() ); + return converter.toJSValueRef(email->getHtmlBody()); + } + else + { + return JSValueMakeUndefined(context); + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Platform execution"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + + return JSValueMakeUndefined(context); +} + +bool JSMessageBody::setHtmlBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + + LogDebug("setHtmlBody"); + + Try + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Api::Messaging::IMessagePtr msg = getMessage(context, object); + + if (msg->getMessageType() == Api::Messaging::EMAIL) + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + std::string body = converter.toString(value); + LogDebug("input String : " << body); + email->setHtmlBody(body); + return true; + } + else + { + LogError("html body is for Email only."); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError("Error on pointer, null value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("Platform execution"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return false; +} + +Api::Messaging::IMessagePtr JSMessageBody::getMessage(JSContextRef context, + JSValueRef value) +{ + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + return getMessage(context, converter.toJSObjectRef(value)); +} + +Api::Messaging::IMessagePtr JSMessageBody::getMessage(JSContextRef context, + JSObjectRef object) +{ + // private object of thisObject + return getPrivate(object)->getObject(); +} + +JSMessageBodyPrivate* JSMessageBody::getPrivate(JSObjectRef thisObject) +{ + JSMessageBodyPrivate* thisPrivate = + static_cast(JSObjectGetPrivate(thisObject)); + if (!thisPrivate) { + LogError("no private"); + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return thisPrivate; +} + +} +} + + diff --git a/src/standards/Tizen/Messaging/JSMessageBody.h b/src/standards/Tizen/Messaging/JSMessageBody.h new file mode 100755 index 0000000..05feda7 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessageBody.h @@ -0,0 +1,148 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file JSMessage.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGINS_TIZEN_JS_MESSAGE_BODY_H_ +#define WRT_PLUGINS_TIZEN_JS_MESSAGE_BODY_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSMessageBodyPrivate; //IMessagePtr + + +class JSMessageBody +{ + static JSClassRef m_jsClassRef; + +public: + static const JSClassDefinition* getClassInfo(); + static JSClassRef getClassRef(); + + static JSObjectRef createJS( JSContextRef context, const Api::Messaging::IMessagePtr &msg); + +private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getMessageID(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getLoadedStatus(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPlainBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setPlainBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getHtmlBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setHtmlBody(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + /* + * returns private object or throws WrtDeviceApis::Commons::NullPointerException + */ + static JSMessageBodyPrivate* getPrivate(JSObjectRef value); + + /* + * extracts Api Message representation + * throws WrtDeviceApis::Commons::NullPointerException if there's no private object + * throws WrtDeviceApis::Commons::ConversionException if it's not possible to convert to JSObjectRef + */ + static Api::Messaging::IMessagePtr getMessage(JSContextRef context, + JSValueRef value); + + /* + * extracts Api Message representation + * throws WrtDeviceApis::Commons::NullPointerException if there's no private object + */ + static Api::Messaging::IMessagePtr getMessage(JSContextRef context, + JSObjectRef object); + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + +}; + +} +} + +#endif //WRT_PLUGINS_TIZEN_JS_MESSAGE_BODY_H_ + diff --git a/src/standards/Tizen/Messaging/JSMessageFolder.cpp b/src/standards/Tizen/Messaging/JSMessageFolder.cpp new file mode 100755 index 0000000..582ceaf --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessageFolder.cpp @@ -0,0 +1,311 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** +* @file JSMessageFolder.cpp +* @author Oy Kwon (sirot.kwon@samsung.com) +* @version 0.1 +*/ + + +#include +#include +#include +#include +#include +#include +#include +#include + + +#include +#include +#include + +#include "MessagingErrorMsg.h" +#include "JSMessageFolder.h" + +using namespace std; +using namespace DPL; +using namespace TizenApis::Api::Messaging; +using namespace TizenApis::Commons; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassDefinition JSMessageFolder::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "MessageFolder", + NULL, + m_properties, + NULL, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + hasInstance, + NULL +}; + +const char* JSMessageFolder::FOLDERID = "id"; +const char* JSMessageFolder::PARENTID = "parentid"; +const char* JSMessageFolder::ACCOUNTID = "accountid"; +const char* JSMessageFolder::CONTENTTYPE = "contentType"; +const char* JSMessageFolder::NAME = "name"; +const char* JSMessageFolder::PATH = "path"; +const char* JSMessageFolder::TYPE = "type"; +const char* JSMessageFolder::SYNCHRONIZABLE = "synchronizable"; + +const std::string JSMessageFolder::TYPE_SMS = "SMS"; +const std::string JSMessageFolder::TYPE_MMS = "MMS"; +const std::string JSMessageFolder::TYPE_EMAIL = "EMAIL"; + +const std::string JSMessageFolder::FOLDER_INBOX = "INBOX"; +const std::string JSMessageFolder::FOLDER_OUTBOX = "OUTBOX"; +const std::string JSMessageFolder::FOLDER_DRAFTBOX = "DRAFTS"; +const std::string JSMessageFolder::FOLDER_SENTBOX = "SENTBOX"; +const std::string JSMessageFolder::FOLDER_NOTSTANDARD = ""; + + + +JSStaticValue JSMessageFolder::m_properties[] = { + {"id", JSMessageFolder::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"parentid", JSMessageFolder::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"accountid", JSMessageFolder::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"contentType", JSMessageFolder::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"name", JSMessageFolder::getProperty, JSMessageFolder::setProperty, kJSPropertyAttributeNone }, + {"path", JSMessageFolder::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"type", JSMessageFolder::getProperty, NULL, kJSPropertyAttributeReadOnly }, + {"synchronizable", JSMessageFolder::getProperty, JSMessageFolder::setProperty, kJSPropertyAttributeNone }, + {0, 0, 0, 0} +}; + +const JSClassRef JSMessageFolder::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSMessageFolder::getClassInfo() { + return &m_classInfo; +} + +JSClassRef JSMessageFolder::m_jsClassRef = JSClassCreate(JSMessageFolder::getClassInfo()); + +void JSMessageFolder::initialize(JSContextRef context, JSObjectRef object) +{ + LogDebug("JSMessageFolder::initialize "); + JSMessageFolderPriv* priv = static_cast(JSObjectGetPrivate(object)); + + if (priv == NULL) + { + + } + else + { + LogDebug("JSMessageFolder::already exist "); + } +} + + + +JSObjectRef JSMessageFolder::createJSObject(JSContextRef context, IMessageFolderPtr object) +{ + JSMessageFolderPriv* priv = new JSMessageFolderPriv(context, object); + return JSObjectMake(context, getClassRef(), priv); +} + + +void JSMessageFolder::finalize(JSObjectRef object) { + JSMessageFolderPriv* priv = static_cast(JSObjectGetPrivate(object)); + + LogDebug("JSMessageFolder::Finalrize"); + + if (priv != NULL) + { + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +bool JSMessageFolder::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSMessageFolder::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("<<<"); + + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + JSMessageFolderPriv* priv = static_cast(JSObjectGetPrivate(object)); + try + { + if (priv == NULL) + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + IMessageFolderPtr MessageFolder(priv->getObject()); + if(JSStringIsEqualToUTF8CString(propertyName, FOLDERID)) + { + return converter.toJSValueRef(MessageFolder->getId()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, PARENTID)) + { + return converter.toJSValueRef(MessageFolder->getParentId()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, ACCOUNTID)) + { + return converter.toJSValueRef(MessageFolder->getAccountId()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, CONTENTTYPE)) + { + return converter.toJSValueRef(convertMessageType(MessageFolder->getContentType())); + } + else if(JSStringIsEqualToUTF8CString(propertyName, NAME)) + { + return converter.toJSValueRef(MessageFolder->getName()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, PATH)) + { + return converter.toJSValueRef(MessageFolder->getPath()); + } + else if(JSStringIsEqualToUTF8CString(propertyName, TYPE)) + { + return converter.toJSValueRef(convertFolderType(MessageFolder->getType())); + } + else if(JSStringIsEqualToUTF8CString(propertyName, SYNCHRONIZABLE)) + { + return converter.toJSValueRef(MessageFolder->getSynchronizable()); + } + + } + catch (const WrtDeviceApis::Commons::Exception& ex) { + LogError("Exception: " << ex.GetMessage()); + } + return JSValueMakeNull(context); +} + + +bool JSMessageFolder::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("entered"); + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + + Try + { + JSMessageFolderPriv* priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + Api::Messaging::IMessageFolderPtr MessageFolder(priv->getObject()); + + if (JSStringIsEqualToUTF8CString(propertyName, NAME)) { + std::string name = converter.toString(value); + MessageFolder->setName(name); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, SYNCHRONIZABLE)) { + bool synchronizable = converter.toBool(value); + MessageFolder->setSynchronizable(synchronizable); + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogWarning("trying to set incorrect value"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + return false; +} + +bool JSMessageFolder::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +IMessageFolderPtr JSMessageFolder::getMessageFolder(JSContextRef context, JSValueRef value) +{ + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) + { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSMessageFolderPriv *priv = static_cast(JSObjectGetPrivate(object)); + + if (!priv) + { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + return priv->getObject(); +} + +std::string JSMessageFolder::convertMessageType(int msgType){ + + if(msgType == Api::Messaging::SMS){ + return JSMessageFolder::TYPE_SMS; + }else if(msgType == Api::Messaging::MMS){ + return JSMessageFolder::TYPE_MMS; + }else if(msgType == Api::Messaging::EMAIL){ + return JSMessageFolder::TYPE_EMAIL; + }else{ + return NULL; + } + } + +std::string JSMessageFolder::convertFolderType(int msgType){ + + if(msgType == Api::Messaging::INBOX){ + return JSMessageFolder::FOLDER_INBOX; + }else if(msgType == Api::Messaging::OUTBOX){ + return JSMessageFolder::FOLDER_OUTBOX; + }else if(msgType == Api::Messaging::DRAFTBOX){ + return JSMessageFolder::FOLDER_DRAFTBOX; + }else if(msgType == Api::Messaging::SENTBOX){ + return JSMessageFolder::FOLDER_SENTBOX; + }else if(msgType == Api::Messaging::USERDEFINED_FOLDER){ + return JSMessageFolder::FOLDER_NOTSTANDARD; + }else{ + return NULL; + } + } + + +} +}// WrtPlugins + + diff --git a/src/standards/Tizen/Messaging/JSMessageFolder.h b/src/standards/Tizen/Messaging/JSMessageFolder.h new file mode 100755 index 0000000..53114f3 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessageFolder.h @@ -0,0 +1,129 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @file JSMessageFolder.h + * @author Oy Kwon (sirot.kwon@samsung.com) + * @version 0.1 + * @brief Declaration of the Templete class + */ + +#ifndef WRTPLUGINS_TIZEN_JS_MESSAGEFOLDER_H_ +#define WRTPLUGINS_TIZEN_JS_MESSAGEFOLDER_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSMessageFolderPriv; + +class JSMessageFolder { +public: +//@struct JSClassDefinition +// @abstract This structure contains properties and callbacks that define a type of object. All fields other than the version field are optional. Any pointer may be NULL. + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, Api::Messaging::IMessageFolderPtr object); + static Api::Messaging::IMessageFolderPtr getMessageFolder(JSContextRef context, JSValueRef value); + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + static std::string convertMessageType(int msgType); + static std::string convertFolderType(int msgType); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + + /** + * The callback invoked when determining whether an object has a property. + */ + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + /** + * The callback invoked when getting a property's value. + */ + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticValue m_properties[]; + static JSClassRef m_jsClassRef; + + + + static const char* FOLDERID; + static const char* PARENTID; + static const char* ACCOUNTID; + static const char* CONTENTTYPE; + static const char* NAME; + static const char* PATH; + static const char* TYPE; + static const char* SYNCHRONIZABLE; + + static const std::string TYPE_SMS; + static const std::string TYPE_MMS; + static const std::string TYPE_EMAIL; + + static const std::string FOLDER_INBOX; + static const std::string FOLDER_OUTBOX; + static const std::string FOLDER_DRAFTBOX; + static const std::string FOLDER_SENTBOX; + static const std::string FOLDER_NOTSTANDARD; + + +}; + +} +} //WrtPlugins + +#endif //WRTPLUGINS_TIZEN_JS_MESSAGING_SERVICE_MANAGER_H_ + + diff --git a/src/standards/Tizen/Messaging/JSMessagePrivateObject.h b/src/standards/Tizen/Messaging/JSMessagePrivateObject.h new file mode 100755 index 0000000..b692af3 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessagePrivateObject.h @@ -0,0 +1,66 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/** + * + * + * @file JSMessagePrivateObject.h + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef JSMESSAGEPRIVATEOBJECT_H_ +#define JSMESSAGEPRIVATEOBJECT_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +/* + * + */ +class JSMessagePrivateObject : public WrtDeviceApis::CommonsJavaScript::PrivateObjectT + ::Type +{ + public: + JSMessagePrivateObject(JSContextRef context, + const Api::Messaging::IMessagePtr& object) : + WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type(context, object), + m_UpdateMessageReceiver(NULL) + { + } + + void setUpdateMsgReceiver(Api::Messaging::EventUpdateMessageAnswerReceiver* receiver) + { + m_UpdateMessageReceiver = receiver; + } + + Api::Messaging::EventUpdateMessageAnswerReceiver* getUpdateMsgReceiver() const + { + return m_UpdateMessageReceiver; + } + + private: + Api::Messaging::EventUpdateMessageAnswerReceiver* m_UpdateMessageReceiver; // not owned +}; +} +} + +#endif /* JSMESSAGEPRIVATEOBJECT_H_ */ diff --git a/src/standards/Tizen/Messaging/JSMessagingListener.cpp b/src/standards/Tizen/Messaging/JSMessagingListener.cpp new file mode 100755 index 0000000..0185669 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessagingListener.cpp @@ -0,0 +1,799 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @file JSMessagingListener.cpp + * @author Pawel Misiak (p.misiak@samsung.com) + * @version 0.1 + * @brief + */ +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include "MessagingErrorMsg.h" +#include "JSMessagingStorage.h" +#include "ConverterMessage.h" +#include "EventSendMessagePrivateData.h" +#include "JSMessagingListener.h" + +using namespace std; + +namespace TizenApis { +namespace Tizen1_0 { + + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Api::Messaging; +using namespace TizenApis::Commons; + + +JSMessagingListener::JSMessagingListener(JSContextRef context) : + WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type(context), + EventSendMessageAnswerReceiver(ThreadEnum::NULL_THREAD), + EventQueryMessagesAnswerReceiver(ThreadEnum::NULL_THREAD), + EventDeleteMessagesAnswerReceiver(ThreadEnum::NULL_THREAD), + EventUpdateMessagesAnswerReceiver(ThreadEnum::NULL_THREAD), + Api::Messaging::EventUpdateMessageAnswerReceiver(ThreadEnum::NULL_THREAD), + EventMessageReceivedListener(ThreadEnum::NULL_THREAD), + EventQueryConversationsAnswerReceiver(ThreadEnum::NULL_THREAD), + EventDeleteConversationsAnswerReceiver(ThreadEnum::NULL_THREAD), + EventQueryFoldersAnswerReceiver(ThreadEnum::NULL_THREAD), + m_nextHandle(1), + m_emiterMsgId(Api::Messaging::EmitterMessageReceived::emptyId), + m_emiterConvId(Api::Messaging::EmitterConversationReceived::emptyId), + m_emiterFolderId(Api::Messaging::EmitterFolderReceived::emptyId) +{ +} + +void JSMessagingListener::OnAnswerReceived( + const Api::Messaging::EventSendMessagePtr& event) +{ + LogDebug("ENTER"); + + EventSendMessagePrivateDataPtr privateData = + DPL::StaticPointerCast( + event->getPrivateData()); + Assert(NULL != privateData); + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = privateData->getCallbackManager(); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr recipientCallbackManager = + privateData->getRecipientCallbackManager(); + + if (WrtDeviceApis::Commons::ExceptionCodes::None == event->getExceptionCode()) { + if (!event->getRecipient().empty() && recipientCallbackManager) { + ConverterMessage converter(m_context); + JSValueRef recipient = converter.toJSValueRef(event->getRecipient()); + recipientCallbackManager->callOnSuccess(recipient); + } else { + callbackManager->callOnSuccess(); + } + } else { + JSValueRef error = NULL; + switch (event->getExceptionCode()) { + case WrtDeviceApis::Commons::ExceptionCodes::PlatformException: + case WrtDeviceApis::Commons::ExceptionCodes::ConversionException: + error = JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + default: + error = JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + if (!event->getRecipient().empty() && recipientCallbackManager) { + ConverterMessage converter(m_context); + JSValueRef recipient = converter.toJSValueRef(event->getRecipient()); + JSValueRef params[] = { error, recipient }; + recipientCallbackManager->callOnError(params, + sizeof(params) / + sizeof(params[0])); + } else { + callbackManager->callOnError(error); + } + } +} + +void JSMessagingListener::OnAnswerReceived( + const Api::Messaging::EventQueryMessagesPtr& event) +{ + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast(event->getPrivateData()); + Assert(NULL != callbackManager); + LogDebug("thread=" << DPL::Thread::GetCurrentThread()); + + Try + { + if (WrtDeviceApis::Commons::ExceptionCodes::None == event->getExceptionCode()) { + std::vector msgs = event->msgs; + + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(m_context); + + callbackManager->callOnSuccess(converter->toJSValueRef(msgs, this)); + + } else { + switch (event->getExceptionCode()) { + case WrtDeviceApis::Commons::ExceptionCodes::PlatformException: + Throw(WrtDeviceApis::Commons::PlatformException); + case WrtDeviceApis::Commons::ExceptionCodes::ConversionException: + Throw(WrtDeviceApis::Commons::ConversionException); + default: + Throw(WrtDeviceApis::Commons::UnknownException); + } + } + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("platform error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("conversion error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + + Catch(WrtDeviceApis::Commons::UnknownException) { + LogError("unknown error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } +} + +void JSMessagingListener::OnAnswerReceived( + const Api::Messaging::EventDeleteMessagesPtr& event) +{ + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast(event->getPrivateData()); + Assert(NULL != callbackManager); + LogDebug("thread=" << DPL::Thread::GetCurrentThread()); + + Try + { + if (WrtDeviceApis::Commons::ExceptionCodes::None == event->getExceptionCode()) { + callbackManager->callOnSuccess(); + + } else { + switch (event->getExceptionCode()) { + case WrtDeviceApis::Commons::ExceptionCodes::PlatformException: + Throw(WrtDeviceApis::Commons::PlatformException); + case WrtDeviceApis::Commons::ExceptionCodes::ConversionException: + Throw(WrtDeviceApis::Commons::ConversionException); + default: + Throw(WrtDeviceApis::Commons::UnknownException); + } + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("platform error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("conversion error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + + Catch(WrtDeviceApis::Commons::UnknownException) { + LogError("unknown error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + +} + +void JSMessagingListener::OnAnswerReceived( + const Api::Messaging::EventUpdateMessagesPtr& event) +{ + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast(event->getPrivateData()); + Assert(NULL != callbackManager); + LogDebug("thread=" << DPL::Thread::GetCurrentThread()); + + Try + { + if (WrtDeviceApis::Commons::ExceptionCodes::None == event->getExceptionCode()) { + callbackManager->callOnSuccess(); + + } else { + switch (event->getExceptionCode()) { + case WrtDeviceApis::Commons::ExceptionCodes::PlatformException: + Throw(WrtDeviceApis::Commons::PlatformException); + case WrtDeviceApis::Commons::ExceptionCodes::ConversionException: + Throw(WrtDeviceApis::Commons::ConversionException); + default: + Throw(WrtDeviceApis::Commons::UnknownException); + } + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("platform error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("conversion error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + + Catch(WrtDeviceApis::Commons::UnknownException) { + LogError("unknown error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + +} + +void JSMessagingListener::OnAnswerReceived( + const DPL::SharedPtr &event) +{ + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast(event->getPrivateData()); + Assert(NULL != callbackManager); + LogDebug("thread=" << DPL::Thread::GetCurrentThread()); + + Try + { + if (WrtDeviceApis::Commons::ExceptionCodes::None == event->getExceptionCode()) { + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(m_context); + callbackManager->callOnSuccess(converter->toJSValueRef(event->msg, + this)); + } else { + switch (event->getExceptionCode()) { + case WrtDeviceApis::Commons::ExceptionCodes::PlatformException: + Throw(WrtDeviceApis::Commons::PlatformException); + case WrtDeviceApis::Commons::ExceptionCodes::ConversionException: + Throw(WrtDeviceApis::Commons::ConversionException); + default: + Throw(WrtDeviceApis::Commons::UnknownException); + } + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("platform error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("conversion error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + + Catch(WrtDeviceApis::Commons::UnknownException) { + LogError("conversion error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } +} + +void JSMessagingListener::OnAnswerReceived(const Api::Messaging::EventQueryConversationsPtr& event) +{ + LogDebug("enter"); + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast(event->getPrivateData()); + + Try + { + if (WrtDeviceApis::Commons::ExceptionCodes::None == event->getExceptionCode()) + { + vector convPtr = event->getConversatioins(); + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(m_context); + + callbackManager->callOnSuccess(converter->toJSValueRef(convPtr)); + + } + else + { + switch (event->getExceptionCode()) + { + case WrtDeviceApis::Commons::ExceptionCodes::PlatformException: + Throw(WrtDeviceApis::Commons::PlatformException); + case WrtDeviceApis::Commons::ExceptionCodes::ConversionException: + Throw(WrtDeviceApis::Commons::ConversionException); + default: + Throw(WrtDeviceApis::Commons::UnknownException); + } + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) + { + LogError("platform error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + Catch(WrtDeviceApis::Commons::ConversionException) + { + LogError("conversion error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + Catch(WrtDeviceApis::Commons::UnknownException) + { + LogError("unknown error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + +} + +void JSMessagingListener::OnAnswerReceived(const Api::Messaging::EventDeleteConversationsPtr& event) +{ + LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast(event->getPrivateData()); + try + { + if (WrtDeviceApis::Commons::ExceptionCodes::None == event->getExceptionCode()) + { + callbackManager->callOnSuccess(); + +} + else + { + switch (event->getExceptionCode()) + { + case WrtDeviceApis::Commons::ExceptionCodes::PlatformException: + Throw(WrtDeviceApis::Commons::PlatformException); + case WrtDeviceApis::Commons::ExceptionCodes::ConversionException: + Throw(WrtDeviceApis::Commons::ConversionException); + default: + Throw(WrtDeviceApis::Commons::UnknownException); + } + } + } + Catch(WrtDeviceApis::Commons::PlatformException) + { + LogError("platform error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + Catch(WrtDeviceApis::Commons::ConversionException) + { + LogError("conversion error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + Catch(WrtDeviceApis::Commons::UnknownException) + { + LogError("unknown error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } +} + +void JSMessagingListener::OnAnswerReceived(const Api::Messaging::EventQueryFoldersPtr& event) +{ + LogDebug("enter"); + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast(event->getPrivateData()); + + Try + { + if (WrtDeviceApis::Commons::ExceptionCodes::None == event->getExceptionCode()) + { + vector folderPtr = event->getFolders(); + int size = folderPtr.size(); + LogDebug(size); + + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(m_context); + callbackManager->callOnSuccess(converter->toJSValueRef(folderPtr)); + } + else + { + switch (event->getExceptionCode()) + { + case WrtDeviceApis::Commons::ExceptionCodes::PlatformException: + Throw(WrtDeviceApis::Commons::PlatformException); + case WrtDeviceApis::Commons::ExceptionCodes::ConversionException: + Throw(WrtDeviceApis::Commons::ConversionException); + default: + Throw(WrtDeviceApis::Commons::UnknownException); + } + } + } + + Catch(WrtDeviceApis::Commons::PlatformException) + { + LogError("platform error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + Catch(WrtDeviceApis::Commons::ConversionException) + { + LogError("conversion error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + Catch(WrtDeviceApis::Commons::UnknownException) + { + LogError("unknown error"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(m_context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + +} + + +void JSMessagingListener::onAnswerReceived( + const Api::Messaging::EventMessageReceivedPtr& event) +{ + LogDebug("<<<"); + + if (WrtDeviceApis::Commons::ExceptionCodes::None != event->getExceptionCode()) + { + LogError("exception occured: " << event->getExceptionCode()); + return; + } + + JSValueRef jsMsg = NULL; + + EventOnMessagingStorageChangesPrivateDataPtr multiCallbacks = + DPL::DynamicPointerCast(event->getPrivateData()); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr defaultCbm = multiCallbacks->getMessagesAdded(); + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(m_context); + + switch(multiCallbacks->getFunctionIndex()) + { + case MESSAGES_MULTI_FUNCTION: + { + + Api::Tizen::FilterPtr filter = multiCallbacks->getFilter(); + if(filter != NULL) + { + LogDebug("Filter exist"); + Platform::Messaging::StorageChangesMessageGeneratorPtr queryGenerator(new Platform::Messaging::StorageChangesMessageGenerator(event->getMessage())); + + Api::Tizen::IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast(queryGenerator); + filter->travel(filterVisitor, 0); + std::vector msgs; // for msg + Api::Messaging::IMessagePtr msg = event->getMessage(); + if(queryGenerator->getCompareResult()) + { + LogDebug("Message call back"); + msgs.push_back(msg); + jsMsg = converter->toJSValueRef(msgs, this); + } + else + { + LogDebug("skip"); + return; + } + } + else + { + LogDebug("Filter not exist"); + std::vector msgs; // for msg + Api::Messaging::IMessagePtr msg = event->getMessage(); + msgs.push_back(msg); + jsMsg = converter->toJSValueRef(msgs, this); + } + } + break; + case CONVERSATIONS_MULTI_FUNCTION: + { + Api::Tizen::FilterPtr filter = multiCallbacks->getFilter(); + if(filter != NULL) + { + LogDebug("Filter exist"); + Platform::Messaging::StorageChangesConversationGeneratorPtr queryGenerator(new Platform::Messaging::StorageChangesConversationGenerator(event->getConversation())); + + Api::Tizen::IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast(queryGenerator); + filter->travel(filterVisitor, 0); + std::vector convPtrs; // for conversation + Api::Messaging::IConversationPtr conversation = event->getConversation(); + if(queryGenerator->getCompareResult()) + { + LogDebug("Message call back"); + convPtrs.push_back(conversation); + jsMsg = converter->toJSValueRef(convPtrs); + } + else + { + LogDebug("skip"); + return; + } + } + else + { + LogDebug("Filter not exist"); + std::vector convPtrs; // for conversation + Api::Messaging::IConversationPtr conversation = event->getConversation(); + + LogDebug("Conversation call back"); + + convPtrs.push_back(conversation); + jsMsg = converter->toJSValueRef(convPtrs); + } + } + break; + case FOLDERS_MULTI_FUNCTION: + { + Api::Tizen::FilterPtr filter = multiCallbacks->getFilter(); + if(filter != NULL) + { + LogDebug("Filter exist"); + Platform::Messaging::StorageChangesFolderGeneratorPtr queryGenerator(new Platform::Messaging::StorageChangesFolderGenerator(event->getMessageFolder())); + + Api::Tizen::IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast(queryGenerator); + filter->travel(filterVisitor, 0); + std::vector folderPtrs; // for messagefoldeer + Api::Messaging::IMessageFolderPtr messagefolder = event->getMessageFolder(); + if(queryGenerator->getCompareResult()) + { + LogDebug("Message call back"); + folderPtrs.push_back(messagefolder); + jsMsg = converter->toJSValueRef(folderPtrs); + } + else + { + LogDebug("skip"); + return; + } + } + else + { + LogDebug("Filter not exist"); + std::vector folderPtrs; // for messagefoldeer + Api::Messaging::IMessageFolderPtr messagefolder = event->getMessageFolder(); + + LogDebug("MessageFolder call back"); + + folderPtrs.push_back(messagefolder); + jsMsg = converter->toJSValueRef(folderPtrs); + } + } + break; + } + + switch(event->getMsg_Event_Type()) + { + case Api::Messaging::EventMessageReceived::MSG_ADDED: + { + multiCallbacks->getMessagesAdded()->callOnSuccess(jsMsg); + } + break; + case Api::Messaging::EventMessageReceived::MSG_UPDATED: + { + defaultCbm = multiCallbacks->getMessagesUpdated(); + defaultCbm->callOnSuccess(jsMsg); + } + break; + case Api::Messaging::EventMessageReceived::MSG_DELETED: + { + defaultCbm = multiCallbacks->getMessagesRemoved(); + defaultCbm->callOnSuccess(jsMsg); + } + break; + default: + { + break; + } + + } +} + +long JSMessagingListener::addIncomingMsgCallback(const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr& cbManager, int funtionIndex) +{ + IncomingMsgCB* callbacks = NULL; + callbacks = &m_MessageCallbacks; + long handle = 0; + + if (NULL == callbacks) { + Throw(WrtDeviceApis::Commons::UnsupportedException); + } + +// long handle = m_nextHandle; + switch(funtionIndex) + { + case MESSAGES_MULTI_FUNCTION: + { + handle = static_cast(m_emiterMsgId); + LogWarning("Message Emitter handle : " << handle); + } + break; + case CONVERSATIONS_MULTI_FUNCTION: + { + handle = static_cast(m_emiterConvId); + LogWarning("Conversation Emitter handle : " << handle); + } + break; + case FOLDERS_MULTI_FUNCTION: + { + handle = static_cast(m_emiterFolderId); + LogWarning("Folder Emitter handle : " << handle); + } + break; + default: + { + LogWarning("Unexpected state"); + } + break; + } +// m_nextHandle++; + + // try to insert new callback + if (!callbacks->insert(std::make_pair(handle, cbManager)).second) { + // callback with this handle already exists! + Throw(WrtDeviceApis::Commons::AlreadyInUseException); + } + + return handle; +} + +void JSMessagingListener::removeIncomingMsgCallback(long handle) +{ + size_t removed = 0; + removed += m_MessageCallbacks.erase(handle); + + // there are duplicate handles + if (removed > 1) { + LogError("Duplicate callback handles!"); + } + Api::Messaging::EmitterMessageReceived::IdType temp_handle; + temp_handle = static_cast(handle); + + if (m_emiterMsgId == temp_handle) { + LogWarning("EmitterMessageReceived registered"); + Api::Messaging::IMessaging::getInstance().removeOnMessageMsgReceived(m_emiterMsgId); + m_emiterMsgId = Api::Messaging::EmitterMessageReceived::emptyId; + } + else if (m_emiterConvId == temp_handle) { + LogWarning("EmitterConversationReceived registered"); + Api::Messaging::IMessaging::getInstance().removeOnMessageConvReceived(m_emiterConvId); + m_emiterConvId = Api::Messaging::EmitterConversationReceived::emptyId; + } + else if (m_emiterFolderId == temp_handle) { + LogWarning("EmitterFolderReceived registered"); + Api::Messaging::IMessaging::getInstance().removeOnMessageFolderReceived(m_emiterFolderId); + m_emiterFolderId = Api::Messaging::EmitterFolderReceived::emptyId; + } + +} + +bool JSMessagingListener::checkMessageReceivedEmitter(int funtionIndex) +{ + bool retVal = FALSE; + + switch(funtionIndex) + { + case MESSAGES_MULTI_FUNCTION: + { + if (m_emiterMsgId != Api::Messaging::EmitterMessageReceived::emptyId) { + LogWarning("Message Emitter Already registered"); + retVal = TRUE; + } + } + break; + case CONVERSATIONS_MULTI_FUNCTION: + { + if (m_emiterConvId != Api::Messaging::EmitterMessageReceived::emptyId) { + LogWarning("Conversation Emitter Already registered"); + retVal = TRUE; + } + } + break; + case FOLDERS_MULTI_FUNCTION: + { + if (m_emiterFolderId != Api::Messaging::EmitterMessageReceived::emptyId) { + LogWarning("MessageFolder Emitter Already registered"); + retVal = TRUE; + } + } + break; + default: + { + LogWarning("Unexpected state"); + } + break; + } + return retVal; +} + + +void JSMessagingListener::registerMessageReceivedEmitter(EventOnMessagingStorageChangesPrivateDataPtr privData) +{ + + if(privData->getFunctionIndex() == MESSAGES_MULTI_FUNCTION) + { + + if (m_emiterMsgId != Api::Messaging::EmitterMessageReceived::emptyId) { + LogWarning("Already registered"); + return; + } + + Api::Messaging::EmitterMessageReceivedPtr emitter(new Api::Messaging::EmitterMessageReceived()); + emitter->setListener(this); + emitter->setEventPrivateData(DPL::StaticPointerCast(privData));// <-registerMessageReceivedEmitter() + m_emiterMsgId = emitter->getId(); + Api::Messaging::IMessaging::getInstance().addOnMessageReceived(emitter, privData->getFilter(), privData->getFunctionIndex()); + } + else if(privData->getFunctionIndex() == CONVERSATIONS_MULTI_FUNCTION) + { + + if (m_emiterConvId != Api::Messaging::EmitterConversationReceived::emptyId) { + LogWarning("Already registered"); + return; + } + + Api::Messaging::EmitterConversationReceivedPtr emitter(new Api::Messaging::EmitterConversationReceived()); + emitter->setListener(this); + emitter->setEventPrivateData(DPL::StaticPointerCast(privData));// <-registerMessageReceivedEmitter() + m_emiterConvId = emitter->getId(); + Api::Messaging::IMessaging::getInstance().addOnMessageReceived(emitter, privData->getFilter(), privData->getFunctionIndex()); + } + else// if(privData->getFunctionIndex() == FOLDERS_MULTI_FUNCTION) + { + + if (m_emiterFolderId != Api::Messaging::EmitterFolderReceived::emptyId) { + LogWarning("Already registered"); + return; + } + + Api::Messaging::EmitterFolderReceivedPtr emitter(new Api::Messaging::EmitterFolderReceived()); + emitter->setListener(this); + emitter->setEventPrivateData(DPL::StaticPointerCast(privData));// <-registerMessageReceivedEmitter() + m_emiterFolderId = emitter->getId(); + Api::Messaging::IMessaging::getInstance().addOnMessageReceived(emitter, privData->getFilter(), privData->getFunctionIndex()); + } + +} + +void JSMessagingListener::deregisterMessageReceivedEmitter() +{ + LogDebug("enter"); + if (m_emiterMsgId != Api::Messaging::EmitterMessageReceived::emptyId) { + LogWarning("EmitterMessageReceived registered"); + Api::Messaging::IMessaging::getInstance().removeOnMessageMsgReceived(m_emiterMsgId); + m_emiterMsgId = Api::Messaging::EmitterMessageReceived::emptyId; + } + + if (m_emiterConvId != Api::Messaging::EmitterConversationReceived::emptyId) { + LogWarning("EmitterConversationReceived registered"); + Api::Messaging::IMessaging::getInstance().removeOnMessageConvReceived(m_emiterConvId); + m_emiterConvId = Api::Messaging::EmitterConversationReceived::emptyId; + } + + if (m_emiterFolderId != Api::Messaging::EmitterFolderReceived::emptyId) { + LogWarning("EmitterFolderReceived registered"); + Api::Messaging::IMessaging::getInstance().removeOnMessageFolderReceived(m_emiterFolderId); + m_emiterFolderId = Api::Messaging::EmitterFolderReceived::emptyId; + } + LogDebug("finish"); + return; +} + +} +} diff --git a/src/standards/Tizen/Messaging/JSMessagingListener.h b/src/standards/Tizen/Messaging/JSMessagingListener.h new file mode 100755 index 0000000..9c21470 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessagingListener.h @@ -0,0 +1,110 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * @file JSMessagingListener.h + * @author Pawel Misiak (p.misiak@samsung.com) + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef JSMESSAGINGLISTENER_H +#define JSMESSAGINGLISTENER_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "MessagingStorageMultiCallback.h" + + + +namespace TizenApis { +namespace Tizen1_0 { +typedef WrtDeviceApis::Commons::EventAnswerReceiver +EventSendMessageAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver +EventQueryMessagesAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver +EventDeleteMessagesAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver +EventUpdateMessagesAnswerReceiver; +typedef WrtDeviceApis::Commons::EventListener +EventMessageReceivedListener; +typedef WrtDeviceApis::Commons::EventAnswerReceiver +EventQueryConversationsAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver +EventDeleteConversationsAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver +EventQueryFoldersAnswerReceiver; + +class JSMessagingListener : public WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type, + public EventSendMessageAnswerReceiver, + public EventQueryMessagesAnswerReceiver, + public EventDeleteMessagesAnswerReceiver, + public EventUpdateMessagesAnswerReceiver, + public Api::Messaging::EventUpdateMessageAnswerReceiver, + public EventMessageReceivedListener, + public EventQueryConversationsAnswerReceiver, + public EventDeleteConversationsAnswerReceiver, + public EventQueryFoldersAnswerReceiver +{ + public: + explicit JSMessagingListener(JSContextRef context); + + long addIncomingMsgCallback(const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr& cbManager, int funtionIndex); + void removeIncomingMsgCallback(long handle); + bool checkMessageReceivedEmitter(int functionIndex); + void registerMessageReceivedEmitter(EventOnMessagingStorageChangesPrivateDataPtr privData); + void deregisterMessageReceivedEmitter(); + + protected: + virtual void OnAnswerReceived( + const DPL::SharedPtr &event); + virtual void OnAnswerReceived( + const DPL::SharedPtr &event); + virtual void OnAnswerReceived( + const DPL::SharedPtr &event); + virtual void OnAnswerReceived( + const DPL::SharedPtr &event); + virtual void OnAnswerReceived( + const DPL::SharedPtr &event); + virtual void OnAnswerReceived(const Api::Messaging::EventQueryConversationsPtr& event); + virtual void OnAnswerReceived(const Api::Messaging::EventDeleteConversationsPtr& event); + virtual void OnAnswerReceived(const Api::Messaging::EventQueryFoldersPtr& event); + virtual void onAnswerReceived(const Api::Messaging::EventMessageReceivedPtr& event); + + private: + typedef std::map IncomingMsgCB; + IncomingMsgCB m_MessageCallbacks; +// IncomingMsgCB m_MessageUpdatedCallbacks; +// IncomingMsgCB m_MessageDeletedCallbacks; + long m_nextHandle; + Api::Messaging::EmitterMessageReceived::IdType m_emiterMsgId; + Api::Messaging::EmitterConversationReceived::IdType m_emiterConvId; + Api::Messaging::EmitterFolderReceived::IdType m_emiterFolderId; +}; + +typedef DPL::SharedPtr JSMessagingListenerPtr; +} +} + +#endif // JSMESSAGINGLISTENER_H diff --git a/src/standards/Tizen/Messaging/JSMessagingService.cpp b/src/standards/Tizen/Messaging/JSMessagingService.cpp new file mode 100755 index 0000000..c70fcca --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessagingService.cpp @@ -0,0 +1,1010 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @file JSPluginTemplete.cpp + * @author Jaehyun Park (jaehyun77.park@samsung.com) + * @version 0.1 + * @brief Implementation of the JSPluginTemplete class + */ + +#include "JSMessagingService.h" +#include "MessagingController.h" +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "MessagingErrorMsg.h" +#include "ConverterMessage.h" +#include "JSMessagingListener.h" +#include "JSMessage.h" +#include "EventSendMessagePrivateData.h" //for send message +#include "EventMessagingServicePrivateData.h" +#include "plugin_config.h" + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Api::Messaging; +using namespace TizenApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { + + JSClassRef JSMessagingService::m_jsClassRef = NULL; + JSClassDefinition JSMessagingService::m_classInfo = { + 0, + kJSClassAttributeNone, + "MessagingService", + NULL, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty,Geolocation + NULL, //getPropertyNames, + NULL, + NULL, + hasInstance, + NULL + }; + + JSStaticValue JSMessagingService::m_property[] = + { + {"accountId", getProperty, NULL, kJSPropertyAttributeReadOnly}, + {"type", getProperty, NULL, kJSPropertyAttributeReadOnly}, + {"name", getProperty, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } + }; + + JSStaticFunction JSMessagingService::m_function[] = { + { "createMessage", JSMessagingService::createMessage, kJSPropertyAttributeNone }, + { "sendMessage", JSMessagingService::sendMessage, kJSPropertyAttributeNone }, + { "loadMessageBody", JSMessagingService::loadMessageBody, kJSPropertyAttributeNone }, +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + { "loadMessageAttachment", JSMessagingService::loadMessageAttachment, kJSPropertyAttributeNone }, +#endif + { "sync", JSMessagingService::sync, kJSPropertyAttributeNone }, + { "syncFolder", JSMessagingService::syncFolder, kJSPropertyAttributeNone }, + { "cancelOperation", JSMessagingService::cancelOperation, kJSPropertyAttributeNone }, + { 0, 0, 0 } + }; + + const JSClassRef JSMessagingService::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; + } + + void JSMessagingService::initialize(JSContextRef context, JSObjectRef object) { + LogDebug("creation messaging Service instance"); + } + + void JSMessagingService::finalize(JSObjectRef object) { + LogDebug("finalize messaging instance"); + //JSMessagingServicePriv *priv = static_cast(JSObjectGetPrivate(object)); + JSMessagingServicePriv *priv = static_cast(JSObjectGetPrivate(object)); + delete priv; + } + + bool JSMessagingService::hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); + } + + JSObjectRef JSMessagingService::createJSObject(JSContextRef context, const Api::Messaging::IMessagingServicePtr &messagingService) + { + JSMessagingServicePriv* priv = new JSMessagingServicePriv( context, messagingService); //make private class. + return JSObjectMake(context, getClassRef(), priv); + } + + JSValueRef JSMessagingService::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) + { + LogDebug("<<< "); + JSValueRef retVal = NULL; + + JSMessagingServicePriv* priv = static_cast(JSObjectGetPrivate(object)); //get private object + if (priv) + { + IMessagingServicePtr imessagingService = priv->getObject(); + Try{ + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context); + + if (JSStringIsEqualToUTF8CString(propertyName, "type")) { + LogDebug("type" << ":" << imessagingService->getType()); + retVal = converter->toJSValueRef(converter->toMessageType(imessagingService->getType())); + } else if (JSStringIsEqualToUTF8CString(propertyName, "name")) { + LogDebug("name" << ":" << imessagingService->getName()); + retVal = converter->toJSValueRef(imessagingService->getName()); + } else if (JSStringIsEqualToUTF8CString(propertyName, "accountId")) { + LogDebug("accountId" << ":" << imessagingService->getAccountID()); + + std::stringstream stream; + stream << imessagingService->getAccountID(); + if (stream.fail()) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException,"Couldn't convert e-mail account id"); + } + + retVal = converter->toJSValueRef(stream.str()); + } else{ + retVal = JSValueMakeUndefined(context); + } + + } Catch (WrtDeviceApis::Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + LogDebug(">>>"); + return retVal; + + } + else + { + LogDebug(" Private Object is NULL "); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_FOUND_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_FOUND); + } + + } + + JSValueRef JSMessagingService::createMessage(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) + { + + LogInfo("<<<"); + LogDebug("arumentConunt:" << argumentCount); + + JSMessagingServicePriv* priv = static_cast(JSObjectGetPrivate(thisObject)); + if (priv) + { + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_CREATE_MESSAGE]); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + try { + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context); + JSContextRef l_globalContext = converter->toJSGlobalContext(thisObject); + Validator check(context, exception); + + IMessagingServicePtr imessagingService = priv->getObject(); //get MessagingService. + JSValueRef objMsg = NULL; + + Api::Messaging::MessageType msgType = (Api::Messaging::MessageType)imessagingService->getType(); + LogInfo("msgType :" << msgType); + + if (msgType == Api::Messaging::EMAIL) + { + Api::Messaging::EmailAccountInfo account = imessagingService->getCurrentEmailAccount(); + LogDebug("Account Address:" << &account); + objMsg = JSMessage::createJSObject(l_globalContext, account, msgType); //make message JSValueRef. + } + else + { + objMsg = JSMessage::createJSObject(l_globalContext, msgType); //make message JSValueRef. + } + + //set Properties + if ( argumentCount == 1) + { + IMessagePtr msg = converter->toIMessage(objMsg) ; + + if (!msg) + ThrowMsg(WrtDeviceApis::Commons::PlatformException,"platform exception"); + + LogDebug ("##### msg type is " << msg->getId()); + + const ScopedJSStringRef subjectStr(JSStringCreateWithUTF8CString("subject")); + const ScopedJSStringRef toStr(JSStringCreateWithUTF8CString("to")); + const ScopedJSStringRef ccStr(JSStringCreateWithUTF8CString("cc")); + const ScopedJSStringRef bccStr(JSStringCreateWithUTF8CString("bcc")); + const ScopedJSStringRef plainBodyStr(JSStringCreateWithUTF8CString("plainBody")); + const ScopedJSStringRef htmlBodyStr(JSStringCreateWithUTF8CString("htmlBody")); + const ScopedJSStringRef priorityStr(JSStringCreateWithUTF8CString("priority")); + + JSObjectRef arg = converter->toJSObjectRef(arguments[0]); + JSValueRef subjectData = JSObjectGetProperty(l_globalContext, arg, subjectStr.get(), NULL); + JSValueRef toData = JSObjectGetProperty(l_globalContext, arg, toStr.get(), NULL); + JSValueRef ccData = JSObjectGetProperty(l_globalContext, arg, ccStr.get(), NULL); + JSValueRef bccData = JSObjectGetProperty(l_globalContext, arg, bccStr.get(), NULL); + JSValueRef plainBodyData = JSObjectGetProperty(l_globalContext, arg, plainBodyStr.get(), NULL); + JSValueRef htmlBodyData = JSObjectGetProperty(l_globalContext, arg, htmlBodyStr.get(), NULL); + JSValueRef priorityData = JSObjectGetProperty(l_globalContext, arg, priorityStr.get(), NULL); + + //subject + if (!JSValueIsUndefined(l_globalContext, subjectData) ) + { + LogDebug ( " Subject : " << converter->toString(subjectData) ); + std::string subject = converter->toString(subjectData); + switch (msgType) + { + case Api::Messaging::MMS: + { + Api::Messaging::IMmsPtr mms = Api::Messaging::MessageFactory::convertToMms(msg); + mms->setSubject(subject); + break; + } + case Api::Messaging::EMAIL: + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + email->setSubject(subject); + break; + } + default: + { + LogError("message not supported"); + //Throw(WrtDeviceApis::Commons::UnsupportedException); + //break; + } + } + } + //to + if (!JSValueIsUndefined(l_globalContext, toData) ) + { + Api::Messaging::Recipients to = converter->toRecipients(toData); + LogDebug("setting to field, size=" << to.getRecipientSize()); + msg->setToRecipients(to); + } + //cc + if (msgType == Api::Messaging::EMAIL ) + { + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + if (!JSValueIsUndefined(l_globalContext, ccData)) + { + Api::Messaging::Recipients cc = converter->toRecipients(ccData); + email->setCcRecipients(cc); + } + + if (!JSValueIsUndefined(l_globalContext, bccData)) + { + Api::Messaging::Recipients bcc = converter->toRecipients(bccData); + email->setBccRecipients(bcc); + } + + if (!JSValueIsUndefined(l_globalContext, htmlBodyData)) + { + std::string body = converter->toString(htmlBodyData); + LogDebug("html body : " << body); + email->setHtmlBody(body); + } + + if (!JSValueIsUndefined(l_globalContext, priorityData)) + { + email->setPriority(converter->toMessagePriority(priorityData)); + } + + } + + if (!JSValueIsUndefined(l_globalContext, plainBodyData) ) + { + std::string body = converter->toString(plainBodyData); + LogDebug("plain body : " << body); + msg->setBody(body); + } + + } + return objMsg; + + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + + LogInfo(">>>"); + return JSValueMakeUndefined(context); + } + else + { + LogDebug(" Private Object is NULL "); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_FOUND_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_FOUND); + } + + } + +JSValueRef JSMessagingService::sendMessage(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + + JSMessagingServicePriv* priv = static_cast(JSObjectGetPrivate(thisObject)); + + if (!priv) { + LogError("Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + JSContextRef globalContext = priv->getContext(); + + LogInfo(">>> argument count : " << argumentCount); + + if (argumentCount < 2) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr recipientCallbackManager; + + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context); + + Try { + + if ( argumentCount > 1 && argumentCount < 4) + { + if ( argumentCount > 1) + { + if (JSValueIsObject(context, arguments[1]) && !Validator(context).isCallback(arguments[1])) //check + { + MessageSendCallback callbacks = converter->toMessageSendCallback(arguments[1]); + callbackManager->setOnSuccess( converter->toFunctionOrNull(callbacks.onSuccess) ); + } + else + { + callbackManager->setOnSuccess(converter->toFunction(arguments[1])); + } + + if ( argumentCount == 3) + { + callbackManager->setOnError(converter->toFunctionOrNull(arguments[2])); + } + } + } + else + { + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException,"invalid argument exception"); + } + + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_SEND_MESSAGE]); + TIZEN_ASYNC_CBM_ACCESS_HANDLER(status, context, callbackManager); + + //create PrivateData + EventSendMessagePrivateDataPtr privateData( new EventSendMessagePrivateData(callbackManager, recipientCallbackManager) ); + + Api::Messaging::EventSendMessagePtr event(new Api::Messaging::EventSendMessage()); + + LogDebug("Event size"); + + IMessagingServicePtr imessagingService = priv->getObject(); + + event->opId = imessagingService->createOpId(MESSAGING_SERVICE_OP_SEND_MESSAGE); + event->msg = converter->toIMessage(arguments[0]); + imessagingService->setMessageToOpId( event->opId, event->msg); + event->store = true; //always store message in sendbox after send , email Type. + event->m_messagingService = imessagingService; + event->setPrivateData(DPL::StaticPointerCast(privateData)); + + //event->setForAsynchronousCall(&JSMessagingListener::getInstance()); + //event->setForAsynchronousCall(&MessagingControllerSingleton::Instance()); + event->setForAsynchronousCall(&MessagingController::getInstance()); + + Api::Messaging::ReqReceiverMessageSingleton::Instance().sendMessage(event); //send message + + return converter->toJSValueRef(event->opId); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT)); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSMessagingService::loadMessageBody(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + + JSMessagingServicePriv* priv = static_cast(JSObjectGetPrivate(thisObject)); + + if (!priv) { + LogError("Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + JSContextRef globalContext = priv->getContext(); //create global Context + LogInfo(">>> argument count : " << argumentCount); + + if (argumentCount < 3) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + Validator check(context, exception); //create check + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext); + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(globalContext); //create converter + + Try { + //create event + EventMessagingServicePrivateDataPtr privateData( new EventMessagingServicePrivateData(callbackManager) ); + + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY]); + TIZEN_ASYNC_CBM_ACCESS_HANDLER(status, context, callbackManager); + + if (JSValueIsObject(context, arguments[0]) && Validator(context).isCallback(arguments[0])) //check + { + callbackManager->setOnSuccess(converter->toFunctionOrNull(arguments[0])); + if (converter->toFunctionOrNull(arguments[1]) && Validator(context).isCallback(arguments[1]) ) + { + callbackManager->setOnError(converter->toFunctionOrNull(arguments[1])); + } + + Api::Messaging::EventMessagingServicePtr event(new Api::Messaging::EventMessagingService()); //create event + if ( JSValueIsObject(context, arguments[2]) ) + { + event->m_message = converter->toIMessage(arguments[2]) ; + LogDebug("Message Type =" << event->m_message->getMessageType()); + privateData->setMessageJSValueRef(arguments[2]); //set Message JSValueRef. + } + else + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + IMessagingServicePtr imessagingService = priv->getObject(); + int opId = imessagingService->createOpId(MESSAGING_SERVICE_OP_DOWNLOAD_BODY); + LogDebug("Operation ID is = " << opId); + + event->opId = opId; + imessagingService->setMessageToOpId(opId, event->m_message); + event->setEventType(EventMessagingService::MESSAGING_SERVICE_EVENT_TYPE_LOAD_MESSAGE_BODY); + event->setPrivateData(DPL::StaticPointerCast(privateData)); + event->setForAsynchronousCall(&MessagingController::getInstance()); + + Api::Messaging::ReqReceiverMessageSingleton::Instance().loadMessageBody(event); //load message Body + + return converter->toJSValueRef(event->opId); + } + else + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + + } + Catch(WrtDeviceApis::Commons::ConversionException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT)); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + + return JSValueMakeNull(context); + +} + +#if 0 // MESSAGING ATTACHMENT IS BLOCKED +JSValueRef JSMessagingService::loadMessageAttachment(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + + JSMessagingServicePriv* priv = static_cast(JSObjectGetPrivate(thisObject)); + + if (!priv) { + LogError("Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + + + } + + JSContextRef globalContext = priv->getContext(); //create global Context + + LogInfo(">>> argument count : " << argumentCount); + + if (argumentCount < 3) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + Validator check(context, exception); //create check + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext); + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(globalContext); //create converter + + Try { + + if (JSValueIsObject(context, arguments[0]) && Validator(context).isCallback(arguments[0])) //check + { + EventMessagingServicePrivateDataPtr privateData( new EventMessagingServicePrivateData(callbackManager) ); + + callbackManager->setOnSuccess(converter->toFunctionOrNull(arguments[0])); + if (converter->toFunctionOrNull(arguments[1]) && Validator(context).isCallback(arguments[1]) ) + { + callbackManager->setOnError(converter->toFunctionOrNull(arguments[1])); + } + + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT]); + TIZEN_ASYNC_CBM_ACCESS_HANDLER(status, context, callbackManager); + + Api::Messaging::EventMessagingServicePtr event(new Api::Messaging::EventMessagingService()); //create event + + LogInfo("event"); + + event->setEventType(EventMessagingService::MESSAGING_SERVICE_EVENT_TYPE_LOAD_MESSAGE_ATTACHMENT); + event->setPrivateData(DPL::StaticPointerCast(privateData)); + event->setForAsynchronousCall(&MessagingController::getInstance()); + LogInfo("agu"); + if (argumentCount == 3 && !JSValueIsNull(context, arguments[2])) + { + Api::Messaging::IAttachmentPtr iAttchmentPtr = converter->toIAttachment(arguments[2]); + privateData->setMessageJSValueRef(arguments[2]); //set Message JSValueRef. + if (iAttchmentPtr) + { + event->m_attachment = iAttchmentPtr; + event->m_message = event->m_attachment->getMessage(); + if (!event->m_message) + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + else + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_FOUND_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_FOUND); + } + } + else + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + LogInfo("pendingOperation"); + JSValueRef pendingOperation = WrtDeviceApis::CommonsJavaScript::makePendingOperation(globalContext, event); //create pendingOperation. + Api::Messaging::ReqReceiverMessageSingleton::Instance().loadMessageAttachment(event); //load message Body + + return pendingOperation; + + } + else + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + } + Catch(WrtDeviceApis::Commons::ConversionException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT)); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + + return JSValueMakeNull(context); +} +#endif + +JSValueRef JSMessagingService::sync(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + + LogDebug("entered"); + JSMessagingServicePriv* priv = static_cast(JSObjectGetPrivate(thisObject)); + + if (priv) { + + JSContextRef globalContext = priv->getContext(); //get global Context + + LogInfo(">>> argument count : " << argumentCount); + + if (argumentCount > 4 || argumentCount < 2 ) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + Validator check(context, exception); //check context + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext); + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(globalContext); //create converter + + IMessagingServicePtr imessagingService = priv->getObject(); //get MessagingService. + + Api::Messaging::MessageType msgType = (Api::Messaging::MessageType)imessagingService->getType(); + LogInfo("msgType :" << msgType); + + Try { + + int limit = -1; //sync limit + + if (JSValueIsObject(context, arguments[0]) && Validator(context).isCallback(arguments[0])) //check + { + callbackManager->setOnSuccess(converter->toFunctionOrNull(arguments[0])); + if (converter->toFunctionOrNull(arguments[1]) && Validator(context).isCallback(arguments[1]) ) + { + callbackManager->setOnError(converter->toFunctionOrNull(arguments[1])); + } + + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_SYNC]); + TIZEN_ASYNC_CBM_ACCESS_HANDLER(status, context, callbackManager); + + EventMessagingServicePrivateDataPtr privateData( new EventMessagingServicePrivateData(callbackManager) ); + + Api::Messaging::EventMessagingServicePtr event(new Api::Messaging::EventMessagingService()); //create event + + if (argumentCount == 3 && !JSValueIsNull(context, arguments[2])) + limit = converter->toInt(arguments[2]); + + LogDebug("limit : " << limit); + + event->opId = imessagingService->createOpId(MESSAGING_SERVICE_OP_SYNC); + event->m_sync_account_id = imessagingService->getAccountID() ; + event->m_sync_limit = limit; + event->m_messagingService = imessagingService; + + event->setEventType(EventMessagingService::MESSAGING_SERVICE_EVENT_TYPE_SYNC); + event->setPrivateData(DPL::StaticPointerCast(privateData)); + event->setForAsynchronousCall(&MessagingController::getInstance()); + + Api::Messaging::ReqReceiverMessageSingleton::Instance().sync(event); //load message Body + + return converter->toJSValueRef(event->opId); + + } + else + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT)); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + + } + else + { + LogError("Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + return JSValueMakeNull(context); + +} + + +JSValueRef JSMessagingService::syncFolder(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + LogDebug("entered"); + + JSMessagingServicePriv* priv = static_cast(JSObjectGetPrivate(thisObject)); + + if (priv) { + JSContextRef globalContext = priv->getContext(); //get global Context + +#if 0 + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + globalContext, + MESSAGING_FUNCTION_API_SYNC); +#endif + LogInfo(">>> argument count : " << argumentCount); + + if (argumentCount > 4 || argumentCount < 1) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + Validator check(context, exception); //check context + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext); + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(globalContext); //create converter + + IMessagingServicePtr imessagingService = priv->getObject(); //get MessagingService. + + + Api::Messaging::MessageType msgType = (Api::Messaging::MessageType)imessagingService->getType(); + LogInfo("msgType :" << msgType); + + Try { + + int limit = -1; + + if (JSValueIsObject(context, arguments[0]) && !Validator(context).isCallback(arguments[0])) //check + { + + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_SYNC_FOLDER]); + TIZEN_ASYNC_CBM_ACCESS_HANDLER(status, context, callbackManager); + + EventMessagingServicePrivateDataPtr privateData( new EventMessagingServicePrivateData(callbackManager) ); + //private->setSyncAccountID( imessagingService->getAccountID()); //set account ID + + Api::Messaging::EventMessagingServicePtr event(new Api::Messaging::EventMessagingService()); //create event + + + IMessageFolderPtr folder = converter->toIMessageFolder(arguments[0]); + if ( folder ) + { + event->m_folder_name = folder->getName(); //it will be changed to the folder ptr + } + + if ( argumentCount > 1 ) + { + if (JSValueIsObject(context, arguments[1]) && Validator(context).isCallback(arguments[1])) //check + { + callbackManager->setOnSuccess(converter->toFunctionOrNull(arguments[1])); + } + + if ( argumentCount > 2 ) + { + if (JSValueIsObject(context, arguments[2]) && Validator(context).isCallback(arguments[2])) //check + { + callbackManager->setOnError(converter->toFunctionOrNull(arguments[2])); + } + } + + if (argumentCount == 4 && !JSValueIsNull(context, arguments[3])) + limit = converter->toInt(arguments[3]); + + } + + LogDebug("limit : " << limit); + LogDebug("folderName : " << event->m_folder_name); + event->opId = imessagingService->createOpId(MESSAGING_SERVICE_OP_SYNC_FOLDER); + event ->m_sync_account_id = imessagingService->getAccountID() ; + event ->m_sync_limit = limit; + event->m_messagingService = imessagingService; + + event->setEventType(EventMessagingService::MESSAGING_SERVICE_EVENT_TYPE_SYNC_FOLDER); + event->setPrivateData(DPL::StaticPointerCast(privateData)); + event->setForAsynchronousCall(&MessagingController::getInstance()); + + Api::Messaging::ReqReceiverMessageSingleton::Instance().syncFolder(event); //load message Body + + return converter->toJSValueRef(event->opId); + + } + else + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + Catch(WrtDeviceApis::Commons::NullPointerException) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT)); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + + } + else + { + LogError("Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + return JSValueMakeNull(context); + + +} + +JSValueRef JSMessagingService::cancelOperation(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + LogDebug("entered"); + + JSMessagingServicePriv* priv = static_cast(JSObjectGetPrivate(thisObject)); //get private object + + if (priv) + { + IMessagingServicePtr imessagingService = priv->getObject(); + Try + { + LogInfo(">>> argument count : " << argumentCount); + + if ( argumentCount == 1 && !Validator(context).isCallback(arguments[0])) + { + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context); + Api::Messaging::MessageType msgType = (Api::Messaging::MessageType)imessagingService->getType(); + LogInfo("msgType :" << msgType); + + int opId = converter->toLong( arguments[0] ); //Fetch operation ID + int handle = imessagingService->getHandleFromOpId(opId); + if ( handle < 0 ) + { + ThrowMsg(WrtDeviceApis::Commons::NotFoundException,"Operation ID Not found"); + } + + int opType = imessagingService->getOpTypeFromOpId(opId); + LogInfo("operation ID :" << opId << " operation Type : " << opType); + + if ( opType == Api::Messaging::MESSAGING_SERVICE_OP_SEND_MESSAGE) + { + IMessagePtr msg = imessagingService->getMessageFromOpId(opId); + if (msg) + { + LogDebug("Call Cancel Function"); + msg->sendCancel(handle); + imessagingService->deleteOpId(opId); + } + } + else + { //for email. + if (msgType == Api::Messaging::EMAIL) + { + if ( opType == Api::Messaging::MESSAGING_SERVICE_OP_DOWNLOAD_BODY ) + { + IMessagePtr msg = imessagingService->getMessageFromOpId(opId); + Api::Messaging::IEmailPtr email = Api::Messaging::MessageFactory::convertToEmail(msg); + LogDebug("Cancel Download Body , handle = " << handle); + email->downloadBodyCancel(handle); + } + else if ( opType == Api::Messaging::MESSAGING_SERVICE_OP_SYNC ) + { + LogDebug("Cancel Sync , handle = " << handle); + imessagingService->syncCancel(handle); + } + else if ( opType == Api::Messaging::MESSAGING_SERVICE_OP_SYNC_FOLDER ) + { + LogDebug("Cancel Sync Folder, handle = " << handle); + imessagingService->syncFolderCancel(handle); + } + imessagingService->deleteOpId(opId); + } + else + { + ThrowMsg(WrtDeviceApis::Commons::UnsupportedException, "Operation Type is mismatched"); + } + } + + } + else + { + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException,"invalid argument exception"); + } + + } + Catch (WrtDeviceApis::Commons::InvalidArgumentException){ + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch (WrtDeviceApis::Commons::NotFoundException){ + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_FOUND_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_FOUND); + } + Catch (WrtDeviceApis::Commons::UnsupportedException){ + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); + } + Catch (WrtDeviceApis::Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + } + else + { + LogDebug(" Private Object is NULL "); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_FOUND_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_FOUND); + } + + LogDebug(">>>"); + return JSValueMakeNull(context); +} + +} +} + diff --git a/src/standards/Tizen/Messaging/JSMessagingService.h b/src/standards/Tizen/Messaging/JSMessagingService.h new file mode 100755 index 0000000..32d8198 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessagingService.h @@ -0,0 +1,110 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +#ifndef WRT_PLUGINS_TIZEN_JS_MESSAGING_SERVICE_H_ +#define WRT_PLUGINS_TIZEN_JS_MESSAGING_SERVICE_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSMessagingServicePriv; + +class JSMessagingService { + +public : + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, const Api::Messaging::IMessagingServicePtr &messagingService); + +private : + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + /** + * The callback invoked when determining whether an object has a property. + */ + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + + /** + * The callback invoked when create message + */ + static JSValueRef createMessage(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef sendMessage(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef loadMessageBody(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); +#if 0 // MESSAGING ATTACHMENT IS BLOCKED + static JSValueRef loadMessageAttachment(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); +#endif + static JSValueRef sync(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef syncFolder(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef cancelOperation(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + static JSStaticFunction m_function[]; + static JSStaticValue m_property[]; + static JSClassRef m_jsClassRef; + +}; //JSMessagingService + +} +} //WrtPlugins + + +#endif //WRT_PLUGINS_TIZEN_JS_MESSAGING_SERVICE_H_ diff --git a/src/standards/Tizen/Messaging/JSMessagingServiceManager.cpp b/src/standards/Tizen/Messaging/JSMessagingServiceManager.cpp new file mode 100755 index 0000000..27e2eb5 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessagingServiceManager.cpp @@ -0,0 +1,352 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @file JSPluginTemplete.cpp + * @author Jaehyun Park (jaehyun77.park@samsung.com) + * @version 0.1 + * @brief Implementation of the JSPluginTemplete class + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "JSMessagingServiceManager.h" +#include "MessagingController.h" +#include "ConverterMessage.h" +#include "plugin_config.h" +#include "MessagingErrorMsg.h" + +using namespace std; +using namespace DPL; +using namespace TizenApis::Api::Messaging; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Commons; + + +namespace TizenApis { +namespace Tizen1_0 { + + JSClassRef JSMessagingServiceManager::m_jsClassRef = NULL; + + JSClassDefinition JSMessagingServiceManager::m_classInfo = { + 0, + kJSClassAttributeNone, + "messaging", + NULL, + NULL, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty,Geolocation + NULL, //getPropertyNames, + NULL, + NULL, + hasInstance, + NULL + }; + + JSStaticFunction JSMessagingServiceManager::m_function[] = { + { "getMessagingServices", JSMessagingServiceManager::getMessagingServices, kJSPropertyAttributeNone }, + { 0, 0, 0 } + }; + + const JSClassRef JSMessagingServiceManager::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; + } + + void JSMessagingServiceManager::initialize(JSContextRef context, JSObjectRef object) { + LogDebug("creation messaging instance"); + + JSMessagingServiceManagerPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (priv == NULL) + { + IMessagingServiceManagerPtr MessagingServiceManager(MessagingFactory::getInstance().getMessagingServiceManager()); + priv = new JSMessagingServiceManagerPriv( context, MessagingServiceManager); + + if(!JSObjectSetPrivate(object, static_cast(priv))) { + LogError("Object can't store private data."); + delete priv; + } + } + else + { + LogDebug("already exist"); + LogDebug("global context=" << priv->getContext()); + } + + } + + void JSMessagingServiceManager::finalize(JSObjectRef object) { + LogDebug("enter"); + JSMessagingServiceManagerPriv* priv = static_cast(JSObjectGetPrivate(object)); + + if (priv) { + JSObjectSetPrivate(object, NULL); + delete priv; // object will be deleted, but used to show that private object is deleted + } + LogDebug("Leave"); + + } + + bool JSMessagingServiceManager::hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); + } + + JSValueRef JSMessagingServiceManager::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) + { + return JSValueMakeUndefined(context); + } + +JSValueRef JSMessagingServiceManager::getMessagingServices(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) +{ + LogInfo("<<<"); + LogDebug("arumentConunt:" << argumentCount); + + JSMessagingServiceManagerPriv* priv = static_cast(JSObjectGetPrivate(thisObject)); + JSContextRef gContext = priv->getContext(); + + assert(priv && "Invalid private pointer."); + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context); + Validator check(context, exception); + + LogInfo(">>> argument count : " << argumentCount); + + //argument[0] : service type + //argument[1] : success callback + //argument[2] : error callback (optional) + //argument[3] : AccountID (optional) + + int messagingType = -1; + int accountId = -1; + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); //create callback manager + + Try{ + if ( argumentCount >= 2 ) + { + if ( !check.isCallback(arguments[0]) && check.isCallback(arguments[1])) + { + messagingType = converter->toMessageType(arguments[0]); + callbackManager->setOnSuccess(converter->toFunctionOrNull(arguments[1])); + } + else + { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + if ( argumentCount == 3 ) + { + if ( check.isCallback(arguments[2])) + { + callbackManager->setOnError(converter->toFunctionOrNull(arguments[2])); + } + else + { + std::stringstream ss; + ss << converter->toString(arguments[3]); + ss >> accountId; + LogDebug("acount Id : " << accountId ); + } + + } + + if ( argumentCount == 4 ) + { + if ( check.isCallback(arguments[2])) + { + callbackManager->setOnError(converter->toFunctionOrNull(arguments[2])); + } + else + { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + std::stringstream ss; + ss << converter->toString(arguments[3]); + if (ss.fail()) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + ss >> accountId; + LogDebug("acount Id : " << accountId ); + } + + if ( argumentCount > 4 ) + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + else + { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + LogDebug("Messaging Service Type =" << messagingType); + + // JSCallbackManager contains function pointers of successCallback and errorCallback. + // The function pointers is be using to return results to Javascriptcore. So JSCallbackManager should be executed by main thread. + + LogDebug("setObject"); + callbackManager->setObject(thisObject); + + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), MessagingExportedNames[MESSAGING_FUNCTION_API_GET_MESSAGING_SERVICE]); + TIZEN_ASYNC_CBM_ACCESS_HANDLER(status, context, callbackManager); + + LogDebug("create event"); + EventGetMessagingServicePtr event(new EventGetMessagingService()); //create event + LogDebug("pendingOperation"); + + LogDebug("IMessagingServiceManagerPtr"); + IMessagingServiceManagerPtr messagingServiceManager(priv->getObject()); + LogDebug("setPrivateData"); + event->setPrivateData(StaticPointerCast (callbackManager)); //callback manager + LogDebug("setForAsynchronousCall"); + event->setForAsynchronousCall(&MessagingController::getInstance()); + + event->setEventType(EventGetMessagingService::MESSAGING_SERVICE_MANAGER_EVENT_TYPE_ALL); + if ( accountId >= 0 ) //if vaild account id + event->setAccountID(accountId); + event->setMessagingServiceType(messagingType); + + messagingServiceManager->getMessagingServiceManager(event); //call postEvent + + }Catch (WrtDeviceApis::Commons::PendingOperationException){ + + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); + + }Catch (WrtDeviceApis::Commons::ConversionException){ + + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + + }Catch (WrtDeviceApis::Commons::InvalidArgumentException){ + + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + + }Catch(WrtDeviceApis::Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage() << " Code: " << _rethrown_exception.getCode()); + + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + LogInfo(">>>"); + return JSValueMakeNull(context); +} + +#if 0 + JSValueRef JSMessagingServiceManager::getMessagingService(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) + { + LogInfo("<<<"); + LogDebug("arumentConunt:" << argumentCount); + + JSMessagingServiceManagerPriv* priv = static_cast(JSObjectGetPrivate(thisObject)); + JSContextRef gContext = priv->getContext(); + + assert(priv && "Invalid private pointer."); + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Validator check(context, exception); + + LogInfo(">>> argument count : " << argumentCount); + + int messagingServiceType = -1; + int accountID = -1; // account not implemente yet. + + //check arguments. + if (!check.isCallback(arguments[0]) || !check.isCallback(arguments[1])) { + LogError("Wrong callbacks parameters"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } else if ( argumentCount != 4) { + LogError("Wrong parameters count :" << argumentCount); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } else { + accountID = converter.toLong(arguments[2]); + messagingServiceType = converter.toLong(arguments[3]); + } + + LogDebug("Messaging Service Type =" << messagingServiceType); + + // JSCallbackManager contains function pointers of successCallback and errorCallback. + // The function pointers is be using to return results to Javascriptcore. So JSCallbackManager should be executed by main thread. + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr cbm(JSCallbackManager::createObject(priv->getContext(), arguments[0], arguments[1])); + cbm->setObject(thisObject); + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_GET_MESSAGING_SERVICE]); + TIZEN_ASYNC_CBM_ACCESS_HANDLER(status, context, cbm); + + EventGetMessagingServicePtr event(new EventGetMessagingService()); //create event + JSObjectRef pendingOperation = WrtDeviceApis::CommonsJavaScript::makePendingOperation(gContext, event); + + Try{ + IMessagingServiceManagerPtr messagingServiceManager(priv->getObject()); + + event->setPrivateData(StaticPointerCast (cbm)); + event->setForAsynchronousCall(&MessagingController::getInstance()); + + event->setEventType(EventGetMessagingService::MESSAGING_SERVICE_MANAGER_EVENT_TYPE_ACCOUNT); + event->setAccountID(accountID); + event->setMessagingServiceType(messagingServiceType); + + messagingServiceManager->getMessagingServiceManager(event); //call postEvent + }Catch (WrtDeviceApis::Commons::PendingOperationException){ + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED)); + }Catch (WrtDeviceApis::Commons::ConversionException){ + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH)); + }Catch (WrtDeviceApis::Commons::InvalidArgumentException){ + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT)); + }Catch(WrtDeviceApis::Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage() << " Code: " << _rethrown_exception.getCode()); + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN)); + } + + LogInfo(">>>"); + return pendingOperation; + } +#endif + +} +} + diff --git a/src/standards/Tizen/Messaging/JSMessagingServiceManager.h b/src/standards/Tizen/Messaging/JSMessagingServiceManager.h new file mode 100755 index 0000000..e43d7d8 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessagingServiceManager.h @@ -0,0 +1,107 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @file JSPluginTemplete.h + * @author Jaehyun Park (jaehyun77.park@samsung.com) + * @version 0.1 + * @brief Declaration of the Templete class + */ + +#ifndef WRTPLUGINS_TIZEN_JS_MESSAGING_SERVICE_MANAGER_H_ +#define WRTPLUGINS_TIZEN_JS_MESSAGING_SERVICE_MANAGER_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSMessagingServiceManagerPriv; + +class JSMessagingServiceManager { +public: +//@struct JSClassDefinition +// @abstract This structure contains properties and callbacks that define a type of object. All fields other than the version field are optional. Any pointer may be NULL. + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + + /** + * The callback invoked when determining whether an object has a property. + */ + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + /** + * The callback invoked when getting a property's value. + */ + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getMessagingServices(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef getMessagingService(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + static JSStaticValue m_property[]; + static JSClassRef m_jsClassRef; + +private: + enum{ + GET_MESSAGING_SERVICE_ALL = 1, + GET_MESSAGING_SERVICE_ACOUNT = 2 + }; + +}; + +} +} //WrtPlugins + +#endif //WRTPLUGINS_TIZEN_JS_MESSAGING_SERVICE_MANAGER_H_ + diff --git a/src/standards/Tizen/Messaging/JSMessagingStorage.cpp b/src/standards/Tizen/Messaging/JSMessagingStorage.cpp new file mode 100755 index 0000000..68c1278 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessagingStorage.cpp @@ -0,0 +1,1107 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @file JSPluginTemplete.cpp + * @author Jaehyun Park (jaehyun77.park@samsung.com) + * @version 0.1 + * @brief Implementation of the JSPluginTemplete class + */ + +#include "JSMessagingStorage.h" +#include "JSMessagingListener.h" +#include "ConverterMessage.h" +#include "MessagingStorageMultiCallback.h" +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "MessagingErrorMsg.h" +#include "plugin_config.h" + + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Tizen1_0::Tizen; +using namespace TizenApis::Commons; + + +namespace TizenApis { +namespace Tizen1_0 { + + JSClassRef JSMessagingStorage::m_jsClassRef = NULL; + + JSClassDefinition JSMessagingStorage::m_classInfo = { + 0, + kJSClassAttributeNone, + "messagingStorage", + NULL, + NULL, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty,Geolocation + NULL, //getPropertyNames, + NULL, + NULL, + hasInstance, + NULL + }; + + JSStaticFunction JSMessagingStorage::m_function[] = { + { "findMessages", JSMessagingStorage::findMessages, kJSPropertyAttributeNone }, + { "removeMessages", JSMessagingStorage::removeMessages, kJSPropertyAttributeNone }, + { "updateMessages", JSMessagingStorage::updateMessages, kJSPropertyAttributeNone }, + { "findConversations", JSMessagingStorage::findConversations, kJSPropertyAttributeNone }, + { "removeConversations", JSMessagingStorage::removeConversations, kJSPropertyAttributeNone }, + { "findFolders", JSMessagingStorage::findFolders, kJSPropertyAttributeNone }, + { "addMessagesChangeListener", JSMessagingStorage::addMessagesChangeListener, kJSPropertyAttributeNone }, + { "addConversationsChangeListener", JSMessagingStorage::addConversationsChangeListener, kJSPropertyAttributeNone }, + { "addFoldersChangeListener", JSMessagingStorage::addFoldersChangeListener, kJSPropertyAttributeNone }, + { "removeChangeListener", JSMessagingStorage::removeChangeListener, kJSPropertyAttributeNone }, + { 0, 0, 0 } + }; + + const JSClassRef JSMessagingStorage::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; + } + + void JSMessagingStorage::initialize(JSContextRef context, JSObjectRef object) { + LogDebug("creation messaging instance"); + + JSMessagingListener* priv = new JSMessagingListener(context); + JSObjectSetPrivate(object, static_cast(priv)); + LogDebug("global context=" << priv->getContext()); + + } + + void JSMessagingStorage::finalize(JSObjectRef object) { + LogDebug("enter"); + JSMessagingListener* priv = + static_cast(JSObjectGetPrivate(object)); + if (priv) { + // deregister from incoming message notifications + priv->deregisterMessageReceivedEmitter(); + + LogDebug("deleting private object (messaging)"); + // for messaging object, private object is shared pointer, so will be deleted automatically + delete priv; + // object will be deleted, but used to show that private object is deleted + JSObjectSetPrivate(object, NULL); + } + + } + + bool JSMessagingStorage::hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); + } + + JSValueRef JSMessagingStorage::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) + { + LogDebug("<<< "); + JSValueRef retVal = NULL; + + Try{ + Converter convert(context); + if (JSStringIsEqualToUTF8CString(propertyName, "FOLDER_INBOX")) { + LogDebug("FOLDER_INBOX" << ":" << "1"); + retVal = convert.toJSValueRef(Api::Messaging::INBOX); + } else if (JSStringIsEqualToUTF8CString(propertyName, "FOLDER_OUTBOX")) { + LogDebug("FOLDER_OUTBOX" << ":" << "2"); + retVal = convert.toJSValueRef(Api::Messaging::OUTBOX); + } else if (JSStringIsEqualToUTF8CString(propertyName, "FOLDER_DRAFTS")) { + LogDebug("FOLDER_DRAFTS" << ":" << "3"); + retVal = convert.toJSValueRef(Api::Messaging::DRAFTBOX); + } else if (JSStringIsEqualToUTF8CString(propertyName, "FOLDER_SENTBOX")) { + LogDebug("FOLDER_SENTBOX" << ":" << "4"); + retVal = convert.toJSValueRef(Api::Messaging::SENTBOX); + } else{ + retVal = JSValueMakeUndefined(context); + } + }Catch (WrtDeviceApis::Commons::Exception){ + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + + } + + LogDebug(">>>"); + return retVal; + } + + JSValueRef JSMessagingStorage::findMessages(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) { + + LogDebug("<<<"); + + JSMessagingListener* priv = static_cast + (JSObjectGetPrivate(thisObject)); + + if (!priv) { + LogError(">>> Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + + } + + JSContextRef globalContext = priv->getContext(); + + if (argumentCount < 2) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + + } + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext); + + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context); + Try { + + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_FIND_MESSAGES]); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Api::Messaging::EventQueryMessagesPtr event(new Api::Messaging::EventQueryMessages()); + + FilterConverterFactory::ConverterType filterConverter = FilterConverterFactory::getConverter(context); + + Api::Tizen::FilterPtr filter = filterConverter->toFilter(arguments[0]); + event->setFilter(filter); + + callbackManager->setOnSuccess(converter->toFunction(arguments[1])); + + if(argumentCount > 2) + { + callbackManager->setOnError(converter->toFunctionOrNull(arguments[2])); + } + + if ((argumentCount >= 3) && !JSValueIsNull(context, arguments[0]) && !JSValueIsUndefined(context, arguments[0])) { + switch(argumentCount){ + case 6:{ + long offset = filterConverter->toLong(arguments[5]); + LogDebug("offset:" << offset); + event->setOffset(offset); + } + case 5:{ + long limit = filterConverter->toLong(arguments[4]); + LogDebug("limit:" << limit); + event->setLimit(limit); + } + case 4:{ + Api::Tizen::SortModePtr sortMode = filterConverter->toSortMode(arguments[3]); + event->setSortMode(sortMode); + break; + } + } + } + + event->setPrivateData(DPL::StaticPointerCast(callbackManager)); + event->setForAsynchronousCall(priv); + + Api::Messaging::ReqReceiverMessageSingleton::Instance().queryMessages(event); + + LogError(">>>"); + return JSValueMakeNull(context); + }Catch(WrtDeviceApis::Commons::ConversionException) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + }Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + }Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + LogError(">>> InvalidValuesException"); + if(argumentCount < 3) + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT)); + }Catch(WrtDeviceApis::Commons::PlatformException) { + LogError(">>> UnknownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + LogError(">>> JSValueMakeNull"); + return JSValueMakeNull(context); + } + + JSValueRef JSMessagingStorage::removeMessages(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) { + + LogDebug("enter"); + + JSMessagingListener* priv = static_cast + (JSObjectGetPrivate(thisObject)); + + if (!priv) { + LogError("Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + + } + + JSContextRef globalContext = priv->getContext(); + + if (argumentCount < 1) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext); + + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context); + Try { + + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_REMOVE_MESSAGES]); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Api::Messaging::EventDeleteMessagesPtr event(new Api::Messaging::EventDeleteMessages()); + + + if (argumentCount > 1) { + callbackManager->setOnSuccess(converter->toFunctionOrNull(arguments[1])); + } + + if (argumentCount > 2) { + callbackManager->setOnError(converter->toFunctionOrNull(arguments[2])); + } + + std::vector msgs; + + JSObjectRef objArg = converter->toJSObjectRef(arguments[0]); + LogDebug("array length "<toIMessage(arg); + msgs.push_back(msg); + } + event->msgArray = msgs; + + event->setPrivateData(DPL::StaticPointerCast(callbackManager)); + event->setForAsynchronousCall(priv); + + Api::Messaging::ReqReceiverMessageSingleton::Instance().deleteMessages(event); + + return JSValueMakeNull(context); + }Catch(WrtDeviceApis::Commons::ConversionException) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + }Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + }Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + LogError(">>> InvalidValuesException"); + if(argumentCount < 3) + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT)); + }Catch(WrtDeviceApis::Commons::PlatformException) { + LogError(">>> UnknownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeNull(context); + } + + JSValueRef JSMessagingStorage::updateMessages(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) { + + LogDebug("enter"); + + JSMessagingListener* priv = static_cast + (JSObjectGetPrivate(thisObject)); + + if (!priv) { + LogError("Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + + } + + JSContextRef globalContext = priv->getContext(); + + if (argumentCount < 1) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject( + globalContext); + + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context); + + Try { + + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_UPDATE_MESSAGES]); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Api::Messaging::EventUpdateMessagesPtr event(new Api::Messaging::EventUpdateMessages()); + + if (argumentCount > 1) { + callbackManager->setOnSuccess(converter->toFunctionOrNull(arguments[1])); + } + + if (argumentCount > 2) { + callbackManager->setOnError(converter->toFunctionOrNull(arguments[2])); + } + + + std::vector msgs; + + JSObjectRef objArg = converter->toJSObjectRef(arguments[0]); + LogDebug("array length "<toIMessage(arg); + msgs.push_back(msg); + } + event->msgArray = msgs; + + event->setPrivateData(DPL::StaticPointerCast( + callbackManager)); + event->setForAsynchronousCall(priv); + + Api::Messaging::ReqReceiverMessageSingleton::Instance().updateMessages(event); + + return JSValueMakeNull(context); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + }Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + }Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + LogError(">>> InvalidValuesException"); + if(argumentCount < 3) + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT)); + }Catch(WrtDeviceApis::Commons::PlatformException) { + LogError(">>> UnknownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeNull(context); + } + + JSValueRef JSMessagingStorage::findConversations(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) + { + + LogDebug("<<<"); + + JSMessagingListener* priv = static_cast + (JSObjectGetPrivate(thisObject)); + + if (!priv) { + LogError(">>> Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + JSContextRef globalContext = priv->getContext(); + + if (argumentCount < 2) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + + } + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext); + + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context); + Try { + + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_FIND_CONVERSATIONS]); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Api::Messaging::EventQueryConversationsPtr event(new Api::Messaging::EventQueryConversations()); + + FilterConverterFactory::ConverterType filterConverter = FilterConverterFactory::getConverter(context); + + Api::Tizen::FilterPtr filter = filterConverter->toFilter(arguments[0]); + event->setFilter(filter); + + callbackManager->setOnSuccess(converter->toFunction(arguments[1])); + + if (argumentCount > 2) + { + callbackManager->setOnError(converter->toFunctionOrNull(arguments[2])); + } + + // setup message filter + if ((argumentCount >= 3) && !JSValueIsNull(context, arguments[0]) && !JSValueIsUndefined(context, arguments[0])) + { + switch(argumentCount) + { + case 6: + { + long offset = filterConverter->toLong(arguments[5]); + LogDebug("offset:" << offset); + event->setOffset(offset); + } + case 5: + { + long limit = filterConverter->toLong(arguments[4]); + LogDebug("limit:" << limit); + event->setLimit(limit); + } + case 4: + { + Api::Tizen::SortModePtr sortMode = filterConverter->toSortMode(arguments[3]); + event->setSortMode(sortMode); + break; + } + } + } + + event->setPrivateData(DPL::StaticPointerCast(callbackManager)); + event->setForAsynchronousCall(priv); + + Api::Messaging::ReqReceiverMessageSingleton::Instance().queryConversations(event); + + return JSValueMakeNull(context); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + }Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + }Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + LogError(">>> InvalidValuesException"); + if(argumentCount < 3) + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT)); + }Catch(WrtDeviceApis::Commons::PlatformException) { + LogError(">>> UnknownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + LogError(">>> JSValueMakeNull"); + return JSValueMakeNull(context); + + + } + + JSValueRef JSMessagingStorage::removeConversations(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) + { + LogDebug("enter"); + + JSMessagingListener* priv = static_cast(JSObjectGetPrivate(thisObject)); + + if (!priv) { + LogError("Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + JSContextRef globalContext = priv->getContext(); + + if (argumentCount < 1) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject( + globalContext); + + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context); + + Try { + + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS]); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Api::Messaging::EventDeleteConversationsPtr event(new Api::Messaging::EventDeleteConversations()); + + if (argumentCount > 1) { + callbackManager->setOnSuccess(converter->toFunctionOrNull(arguments[1])); + } + + if (argumentCount > 2) { + callbackManager->setOnError(converter->toFunctionOrNull(arguments[2])); + } + //check permission. + + std::vector deleteConversationArray = converter->toVectorOfConversation(arguments[0]); + event->setConversations(deleteConversationArray); + event->setFilterUsing(false); + + event->setPrivateData(DPL::StaticPointerCast(callbackManager)); + event->setForAsynchronousCall(priv); + + Api::Messaging::ReqReceiverMessageSingleton::Instance().deleteConversations(event); + + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + }Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + }Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + LogError(">>> InvalidValuesException"); + if(argumentCount < 3) + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT)); + }Catch(WrtDeviceApis::Commons::PlatformException) { + LogError(">>> UnknownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + return JSValueMakeNull(context); + } + + JSValueRef JSMessagingStorage::findFolders(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) + { + + LogDebug("enter"); + + JSMessagingListener* priv = static_cast(JSObjectGetPrivate(thisObject)); + + if (!priv) { + LogError("Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + JSContextRef globalContext = priv->getContext(); + + if (argumentCount < 2) { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext); + ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context); + + // TODO : need to re-implement for supporting filter + Try { + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_FIND_FOLDERS]); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Api::Messaging::EventQueryFoldersPtr event(new Api::Messaging::EventQueryFolders()); + + // setup message filter + FilterConverterFactory::ConverterType filterConverter = FilterConverterFactory::getConverter(context); + + Api::Tizen::FilterPtr filter = filterConverter->toFilter(arguments[0]); + event->setFilter(filter); + + callbackManager->setOnSuccess(converter->toFunction(arguments[1])); + + if(argumentCount > 2) + { + callbackManager->setOnError(converter->toFunctionOrNull(arguments[2])); + } + + event->setPrivateData(DPL::StaticPointerCast(callbackManager)); + event->setForAsynchronousCall(priv); + + Api::Messaging::ReqReceiverMessageSingleton::Instance().queryFolders(event); + + return JSValueMakeNull(context); + + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + }Catch(WrtDeviceApis::Commons::NullPointerException) { + LogError(">>> TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + }Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + LogError(">>> InvalidValuesException"); + if(argumentCount < 3) + { + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT)); + }Catch(WrtDeviceApis::Commons::PlatformException) { + LogError(">>> UnknownException"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + return JSValueMakeNull(context); + } + + JSValueRef JSMessagingStorage::addMessagesChangeListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) { + + LogInfo("<<<"); + LogDebug("arumentConunt:" << argumentCount); + + JSMessagingListener* priv = static_cast + (JSObjectGetPrivate(thisObject)); + + if (!priv) { + LogError("Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + if (argumentCount < 1 || + JSValueIsUndefined(context, arguments[0]) || + JSValueIsNull(context, arguments[0])) + { + LogError("bad argument"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + JSMessagingListener* listener = + static_cast(JSObjectGetPrivate(thisObject)); + if (!listener) { + LogError("no private object"); + return JSValueMakeUndefined(context); + } + + Try + { + + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + JSContextRef l_globalContext = converter->toJSGlobalContext(thisObject); + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = + WrtDeviceApis::CommonsJavaScript::JSCallbackManager::createObject(l_globalContext, + NULL, + NULL); + callbackManager->setObject(thisObject); + + OnMessagesChanged result = converter->toMessageMultifunctions(arguments[0]); + int funtionIndex = result.functionIndex; + + callbackManager->setOnSuccess(result.messagesAdded); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr messagesUpdatedCbm = JSCallbackManager::createObject(listener->getContext(), result.messagesUpdated, NULL); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr messagesRemovedCbm = JSCallbackManager::createObject(listener->getContext(), result.messagesRemoved, NULL); + + messagesUpdatedCbm->setObject(thisObject); + messagesRemovedCbm->setObject(thisObject); + + EventOnMessagingStorageChangesPrivateDataPtr privData( + new EventOnMessagingStorageChangesPrivateData(callbackManager, messagesUpdatedCbm, messagesRemovedCbm, funtionIndex)); + + //filter + if ((argumentCount == 2) && !JSValueIsNull(context, arguments[1]) && !JSValueIsUndefined(context, arguments[1])) + { + FilterConverterFactory::ConverterType filterConverter = FilterConverterFactory::getConverter(context); + privData->setFilter(filterConverter->toFilter(arguments[1])); + } + + if(listener->checkMessageReceivedEmitter(funtionIndex)) + { + LogError("Already in use exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + listener->registerMessageReceivedEmitter(privData); + + // add to map and return index + return JSValueMakeNumber(context, + listener->addIncomingMsgCallback(callbackManager, funtionIndex)); + + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + LogError("Invalid argument exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::UnsupportedException) { + LogError("Unsupported exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); // unsupported type + } + Catch(WrtDeviceApis::Commons::AlreadyInUseException) { + LogError("Already in use exception"); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("not registered for incoming message notifications"); + } + + return JSValueMakeUndefined(context); + } + + JSValueRef JSMessagingStorage::addConversationsChangeListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) { + + LogInfo("<<<"); + LogDebug("arumentConunt:" << argumentCount); + + JSMessagingListener* priv = static_cast + (JSObjectGetPrivate(thisObject)); + + if (!priv) { + LogError("Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + if (argumentCount < 1 || + JSValueIsUndefined(context, arguments[0]) || + JSValueIsNull(context, arguments[0])) + { + LogError("bad argument"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + JSMessagingListener* listener = + static_cast(JSObjectGetPrivate(thisObject)); + if (!listener) { + LogError("no private object"); + return JSValueMakeUndefined(context); + } + + Try + { + + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + JSContextRef l_globalContext = converter->toJSGlobalContext(thisObject); + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = + WrtDeviceApis::CommonsJavaScript::JSCallbackManager::createObject(l_globalContext, + NULL, + NULL); + callbackManager->setObject(thisObject); + + OnMessagesChanged result = converter->toMessageMultifunctions(arguments[0]); + int funtionIndex = result.functionIndex; + + callbackManager->setOnSuccess(result.messagesAdded); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr messagesUpdatedCbm = JSCallbackManager::createObject(listener->getContext(), result.messagesUpdated, NULL); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr messagesRemovedCbm = JSCallbackManager::createObject(listener->getContext(), result.messagesRemoved, NULL); + + messagesUpdatedCbm->setObject(thisObject); + messagesRemovedCbm->setObject(thisObject); + + EventOnMessagingStorageChangesPrivateDataPtr privData( + new EventOnMessagingStorageChangesPrivateData(callbackManager, messagesUpdatedCbm, messagesRemovedCbm, funtionIndex)); + + //filter + if ((argumentCount == 2) && !JSValueIsNull(context, arguments[1]) && !JSValueIsUndefined(context, arguments[1])) + { + FilterConverterFactory::ConverterType filterConverter = FilterConverterFactory::getConverter(context); + privData->setFilter(filterConverter->toFilter(arguments[1])); + } + + if(listener->checkMessageReceivedEmitter(funtionIndex)) + { + LogError("Already in use exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + listener->registerMessageReceivedEmitter(privData); + + // add to map and return index + return JSValueMakeNumber(context, + listener->addIncomingMsgCallback(callbackManager, funtionIndex)); + + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + LogError("Invalid argument exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::UnsupportedException) { + LogError("Unsupported exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); // unsupported type + } + Catch(WrtDeviceApis::Commons::AlreadyInUseException) { + LogError("Already in use exception"); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("not registered for incoming message notifications"); + } + + return JSValueMakeUndefined(context); + } + + + JSValueRef JSMessagingStorage::addFoldersChangeListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) { + + LogInfo("<<<"); + LogDebug("arumentConunt:" << argumentCount); + + JSMessagingListener* priv = static_cast + (JSObjectGetPrivate(thisObject)); + + if (!priv) { + LogError("Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + if (argumentCount < 1 || + JSValueIsUndefined(context, arguments[0]) || + JSValueIsNull(context, arguments[0])) + { + LogError("bad argument"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + JSMessagingListener* listener = + static_cast(JSObjectGetPrivate(thisObject)); + if (!listener) { + LogError("no private object"); + return JSValueMakeUndefined(context); + } + + Try + { + + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(context); + JSContextRef l_globalContext = converter->toJSGlobalContext(thisObject); + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = + WrtDeviceApis::CommonsJavaScript::JSCallbackManager::createObject(l_globalContext, + NULL, + NULL); + callbackManager->setObject(thisObject); + + OnMessagesChanged result = converter->toMessageMultifunctions(arguments[0]); + int funtionIndex = result.functionIndex; + + callbackManager->setOnSuccess(result.messagesAdded); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr messagesUpdatedCbm = JSCallbackManager::createObject(listener->getContext(), result.messagesUpdated, NULL); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr messagesRemovedCbm = JSCallbackManager::createObject(listener->getContext(), result.messagesRemoved, NULL); + + messagesUpdatedCbm->setObject(thisObject); + messagesRemovedCbm->setObject(thisObject); + + EventOnMessagingStorageChangesPrivateDataPtr privData( + new EventOnMessagingStorageChangesPrivateData(callbackManager, messagesUpdatedCbm, messagesRemovedCbm, funtionIndex)); + + //filter + if ((argumentCount == 2) && !JSValueIsNull(context, arguments[1]) && !JSValueIsUndefined(context, arguments[1])) + { + FilterConverterFactory::ConverterType filterConverter = FilterConverterFactory::getConverter(context); + privData->setFilter(filterConverter->toFilter(arguments[1])); + } + + if(listener->checkMessageReceivedEmitter(funtionIndex)) + { + LogError("Already in use exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + listener->registerMessageReceivedEmitter(privData); + + // add to map and return index + return JSValueMakeNumber(context, + listener->addIncomingMsgCallback(callbackManager, funtionIndex)); + + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + LogError("Invalid argument exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + Catch(WrtDeviceApis::Commons::UnsupportedException) { + LogError("Unsupported exception"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); // unsupported type + } + Catch(WrtDeviceApis::Commons::AlreadyInUseException) { + LogError("Already in use exception"); + } + Catch(WrtDeviceApis::Commons::PlatformException) { + LogError("not registered for incoming message notifications"); + } + + return JSValueMakeUndefined(context); + } + + JSValueRef JSMessagingStorage::removeChangeListener(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) + { + LogInfo("entered"); + + JSMessagingListener* priv = static_cast + (JSObjectGetPrivate(thisObject)); + + if (!priv) { + LogError("Null pointer"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + + if (argumentCount < 1) { + LogError("wrong argument count"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + } + + //check permission. + AceSecurityStatus status = MESSAGING_CHECK_ACCESS( + priv->getContext(), + MessagingExportedNames[MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER]); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + JSMessagingListener* listener = + static_cast(JSObjectGetPrivate(thisObject)); + if (!listener) { + LogError("no private object"); + return JSValueMakeUndefined(context); + } + + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Try { + double handler = converter.toDouble(arguments[0]); + listener->removeIncomingMsgCallback(handler); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + LogError("conversion error"); + return JSTizenExceptionFactory::postException(context, exception, + JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH); + } + + return JSValueMakeUndefined(context); + } + + +} +} diff --git a/src/standards/Tizen/Messaging/JSMessagingStorage.h b/src/standards/Tizen/Messaging/JSMessagingStorage.h new file mode 100755 index 0000000..91dd3d7 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSMessagingStorage.h @@ -0,0 +1,123 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @file JSPluginTemplete.h + * @author Jaehyun Park (jaehyun77.park@samsung.com) + * @version 0.1 + * @brief Declaration of the Templete class + */ + +#ifndef WRTPLUGINS_TIZEN_JS_MESSAGING_STORAGE_H_ +#define WRTPLUGINS_TIZEN_JS_MESSAGING_STORAGE_H_ + +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +class JSMessagingStorage { +public: +//@struct JSClassDefinition +// @abstract This structure contains properties and callbacks that define a type of object. All fields other than the version field are optional. Any pointer may be NULL. + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + + /** + * The callback invoked when determining whether an object has a property. + */ + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + /** + * The callback invoked when getting a property's value. + */ + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef findMessages(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef findConversations(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef removeConversations(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef findFolders(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef removeMessages(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef updateMessages(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef addMessagesChangeListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef addConversationsChangeListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef addFoldersChangeListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef removeChangeListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + static JSStaticValue m_property[]; + static JSClassRef m_jsClassRef; + +}; + +} +} //WrtPlugins + +#endif //WRTPLUGINS_TIZEN_JS_MESSAGING_SERVICE_MANAGER_H_ + diff --git a/src/standards/Tizen/Messaging/JSRecipientArray.cpp b/src/standards/Tizen/Messaging/JSRecipientArray.cpp new file mode 100755 index 0000000..1670975 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSRecipientArray.cpp @@ -0,0 +1,390 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @file JSRecipientArray.cpp + * @author Lukasz Marek (l.marel@samsung.com) + * @version 0.1 + */ + +#include +#include "JSRecipientArray.h" +#include +#include + +namespace { +const char* FUNCTION_CONCAT = "concat"; +const char* FUNCTION_JOIN = "join"; +const char* FUNCTION_POP = "pop"; +const char* FUNCTION_PUSH = "push"; +const char* FUNCTION_REVERSE = "reverse"; +const char* FUNCTION_SHIFT = "shift"; +const char* FUNCTION_SLICE = "slice"; +const char* FUNCTION_SORT = "sort"; +const char* FUNCTION_SPLICE = "splice"; +const char* FUNCTION_TOSTRING = "toString"; +const char* FUNCTION_UNSHIFT = "unshift"; +const char* FUNCTION_VALUEOF = "valueOf"; +const char *ARRAY = "Array"; +const char *ATTRIBUTE_LENGTH = "length"; +} +namespace TizenApis { +namespace Tizen1_0 { +JSClassRef JSRecipientArray::m_jsClassRef = NULL; + +JSClassDefinition JSRecipientArray::m_classInfo = { + 0, + kJSClassAttributeNone, + ARRAY, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, //hasInstance, + NULL, //convertToType, +}; + +JSStaticValue JSRecipientArray::m_property[] = { + { ATTRIBUTE_LENGTH, getLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSRecipientArray::m_function[] = { + { FUNCTION_CONCAT, concat, kJSPropertyAttributeNone }, + { FUNCTION_JOIN, join, kJSPropertyAttributeNone }, + { FUNCTION_POP, pop, kJSPropertyAttributeNone }, + { FUNCTION_PUSH, push, kJSPropertyAttributeNone }, + { FUNCTION_REVERSE, reverse, kJSPropertyAttributeNone }, + { FUNCTION_SHIFT, shift, kJSPropertyAttributeNone }, + { FUNCTION_SLICE, slice, kJSPropertyAttributeNone }, + { FUNCTION_SORT, sort, kJSPropertyAttributeNone }, + { FUNCTION_SPLICE, splice, kJSPropertyAttributeNone }, + { FUNCTION_TOSTRING, toString, kJSPropertyAttributeNone }, + { FUNCTION_UNSHIFT, unshift, kJSPropertyAttributeNone }, + { FUNCTION_VALUEOF, valueOf, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSValueRef JSRecipientArray::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + Try + { + JSRecipientArrayPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + Api::Messaging::RecipientsPtr recipients = priv->getObject(); + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + return converter.toJSValueRef(recipients->getRecipientSize()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid conversion"); + } + return JSValueMakeUndefined(context); +} + +Api::Messaging::RecipientsPtr JSRecipientArray::getRecipients(JSContextRef context, + JSObjectRef object) +{ + JSRecipientArrayPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Array contains no private object"); + } + return priv->getObject(); +} + +JSObjectRef JSRecipientArray::createArray(JSContextRef context, + const Api::Messaging::RecipientsPtr &recipients) +{ + + JSRecipientArrayPrivate *priv = new JSRecipientArrayPrivate(context, recipients); + return JSObjectMake(context, getClassRef(), priv); + +} + +const JSClassDefinition* JSRecipientArray::getClassInfo() +{ + return &(m_classInfo); +} + +JSClassRef JSRecipientArray::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +void JSRecipientArray::initialize(JSContextRef context, + JSObjectRef object) +{ + LogDebug("enter"); +} + +void JSRecipientArray::finalize(JSObjectRef object) +{ + LogDebug("enter"); + JSRecipientArrayPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +bool JSRecipientArray::checkValue(const std::string &value) +{ + return true; +} + +bool JSRecipientArray::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Try + { + size_t index = converter.toSizeT(propertyName); + JSRecipientArrayPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + Api::Messaging::RecipientsPtr recipients = priv->getObject(); + if (index < recipients->getRecipientSize()) { + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + //not reporting error is intended + } + return false; +} + +JSValueRef JSRecipientArray::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Try + { + size_t index = converter.toSizeT(propertyName); + JSRecipientArrayPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + Api::Messaging::RecipientsPtr recipients = priv->getObject(); + if (index < recipients->getRecipientSize()) { + std::string result = recipients->getRecipient(index); + if (!result.empty()) { + return converter.toJSValueRef(result); + } + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("invalid property"); + } + return JSValueMakeUndefined(context); +} + +bool JSRecipientArray::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LogDebug("enter"); + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + Try + { + size_t index = converter.toSizeT(propertyName); + std::string address; + if (!JSValueIsUndefined(context, value)) { + address = converter.toString(value); + } + if (!checkValue(address)) { + LogError("trying to assing invalid value"); + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + JSRecipientArrayPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::NullPointerException); + } + Api::Messaging::RecipientsPtr recipients = priv->getObject(); + recipients->setRecipientWithExpand(index, address); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error occured"); + } + return false; +} + +JSValueRef JSRecipientArray::concat(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSRecipientArray::join(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSRecipientArray::pop(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSRecipientArray::push(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSRecipientArray::reverse(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSRecipientArray::shift(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSRecipientArray::slice(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSRecipientArray::sort(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSRecipientArray::splice(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSRecipientArray::toString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSRecipientArray::unshift(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} + +JSValueRef JSRecipientArray::valueOf(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + return JSValueMakeUndefined(context); +} +} +} diff --git a/src/standards/Tizen/Messaging/JSRecipientArray.h b/src/standards/Tizen/Messaging/JSRecipientArray.h new file mode 100755 index 0000000..f5c6438 --- /dev/null +++ b/src/standards/Tizen/Messaging/JSRecipientArray.h @@ -0,0 +1,178 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @file JSRecipientArray.h + * @author Lukasz Marek (l.marel@samsung.com) + * @version 0.1 + */ + +#ifndef _JS_RECIPIENT_ARRAY_H_ +#define _JS_RECIPIENT_ARRAY_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type +JSRecipientArrayPrivate; + +class JSRecipientArray +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + static JSObjectRef createArray(JSContextRef context, + const Api::Messaging::RecipientsPtr &recipients); + + static Api::Messaging::RecipientsPtr getRecipients(JSContextRef context, + JSObjectRef object); + + private: + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef concat(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef join(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef pop(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef push(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef reverse(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef shift(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef slice(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef sort(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef splice(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef toString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef unshift(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef valueOf(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool checkValue(const std::string &value); + + static JSClassRef m_jsClassRef; + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; +}; +} +} + +#endif /* _JS_ARRAY_H_ */ \ No newline at end of file diff --git a/src/standards/Tizen/Messaging/MessageSendCallback.h b/src/standards/Tizen/Messaging/MessageSendCallback.h new file mode 100755 index 0000000..4c3d326 --- /dev/null +++ b/src/standards/Tizen/Messaging/MessageSendCallback.h @@ -0,0 +1,40 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef TIZEN_MESSAGING_MESSAGESENDCALLBACK_H_ +#define TIZEN_MESSAGING_MESSAGESENDCALLBACK_H_ + +#include + +namespace TizenApis { +namespace Tizen1_0 { +struct MessageSendCallback +{ + JSValueRef onSuccess; + JSValueRef onMessageSendSuccess; + JSValueRef onMessageSendError; + + MessageSendCallback() : + onSuccess(NULL), + onMessageSendSuccess(NULL), + onMessageSendError(NULL) + { + } +}; +} +} + +#endif diff --git a/src/standards/Tizen/Messaging/MessagingController.cpp b/src/standards/Tizen/Messaging/MessagingController.cpp new file mode 100755 index 0000000..1c82123 --- /dev/null +++ b/src/standards/Tizen/Messaging/MessagingController.cpp @@ -0,0 +1,293 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author Jaehyun Park (jaehyun77.park@samsung.com) + */ + +#include +#include +#include +#include +#include +#include + +#include "MessagingErrorMsg.h" +#include "MessagingController.h" +#include "JSMessagingService.h" +#include "ConverterMessage.h" +#include "EventSendMessagePrivateData.h" +#include "EventMessagingServicePrivateData.h" +#include +#include "JSMessage.h" + +using namespace std; +using namespace TizenApis::Api::Messaging; +using namespace TizenApis::Commons; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +MessagingController::MessagingController() : + SendMessageAnswerReceiver(ThreadEnum::NULL_THREAD), + GetMessagingServiceReceiver (ThreadEnum::NULL_THREAD), + MessagingServiceReceiver (ThreadEnum::NULL_THREAD) +{ + LogDebug("<<< "); + LogDebug(">>>"); +} + +MessagingController::~MessagingController() { + LogDebug("<<<"); + LogDebug(">>>"); +} + +MessagingController& MessagingController::getInstance() +{ + static MessagingController instance; + return instance; +} + +void MessagingController::OnAnswerReceived(const Api::Messaging::EventGetMessagingServicePtr &event) { + LogDebug("<<<"); + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast (event->getPrivateData()); + + if (event->getExceptionCode() == ExceptionCodes::None) + { + std::vector messagingServices = event->getMessagingServices(); + int count = messagingServices.size(); + int index = 0; + + JSObjectRef jsMessagingServiceObject[count]; //make + + LogDebug(" Service Count :" << count); + + for (index = 0; index < count; index++) + { + jsMessagingServiceObject[index] = JSMessagingService::createJSObject(callbackManager->getContext(), messagingServices[index] ); + } + JSObjectRef result = JSObjectMakeArray(callbackManager->getContext(), count, jsMessagingServiceObject, NULL); + + callbackManager->callOnSuccess(result); + } + else + { + LogDebug("Operation failed. Exception code: " << event->getExceptionCode()); + JSContextRef context = callbackManager->getContext(); + JSValueRef errorObject = NULL; + + WrtDeviceApis::Commons::ExceptionCodes::Enumeration exception = event->getExceptionCode(); + switch(exception) { + case WrtDeviceApis::Commons::ExceptionCodes::InvalidArgumentException: + errorObject = JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + break; + case WrtDeviceApis::Commons::ExceptionCodes::PlatformException: + errorObject = JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::IO_ERROR, JSMESSAGING_EXCEPTION_MSG_IO); + break; + case WrtDeviceApis::Commons::ExceptionCodes::PlatformWrongStateException: + errorObject = JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED); + break; + default: + errorObject = JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + break; + } + callbackManager->callOnError(errorObject); + } + + LogDebug(">>>"); +} + +void MessagingController::OnAnswerReceived(const Api::Messaging::EventMessagingServicePtr &event) +{ + LogDebug(" <<< EventMessagingServicePtr >>> "); + + EventMessagingServicePrivateDataPtr privateData = + DPL::StaticPointerCast(event->getPrivateData()); + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = privateData->getCallbackManager(); //get callback manager + JSContextRef l_globalContext = callbackManager->getContext(); + + int MessagingServiceEventType = event->getEventType(); + LogDebug(" MessagingServiceEvent Type :" << MessagingServiceEventType); + + ConverterMessageFactory::ConverterType converter = + ConverterMessageFactory::getConverter(l_globalContext); + + if (MessagingServiceEventType == EventMessagingService::MESSAGING_SERVICE_EVENT_TYPE_LOAD_MESSAGE_BODY) + { + LogDebug(" Message Sync Folder"); + LogDebug("Operation ID : " << event->opId); + if ( event->m_messagingService) + event->m_messagingService->deleteOpId(event->opId); + + if (event->getExceptionCode() == ExceptionCodes::None) + { + LogDebug(" Message Type :" << event->m_message->getMessageType()); + JSValueRef msg = privateData->getMessageJSValueRef(); + callbackManager->callOnSuccess(msg); + } + else + { + JSValueRef msg = privateData->getMessageJSValueRef(); + callbackManager->callOnError(msg); + } + } + else if (MessagingServiceEventType == EventMessagingService::MESSAGING_SERVICE_EVENT_TYPE_LOAD_MESSAGE_ATTACHMENT) + { + if (event->getExceptionCode() == ExceptionCodes::None) + { + LogDebug(" Message Type :" << event->m_message->getMessageType()); + JSValueRef msg = privateData->getMessageJSValueRef(); + callbackManager->callOnSuccess(msg); + } + else + { + callbackManager->callOnError(); + } + } + else if (MessagingServiceEventType == EventMessagingService::MESSAGING_SERVICE_EVENT_TYPE_SYNC) + { + LogDebug(" Message Sync :"); + LogDebug("Operation ID : " << event->opId); + if ( event->m_messagingService) + event->m_messagingService->deleteOpId(event->opId); + + if (event->getExceptionCode() == ExceptionCodes::None) + { + callbackManager->callOnSuccess(); + } + else + { + callbackManager->callOnError(); + } + } + else if (MessagingServiceEventType == EventMessagingService::MESSAGING_SERVICE_EVENT_TYPE_SYNC_FOLDER) + { + LogDebug(" Message Sync Folder"); + LogDebug("Operation ID : " << event->opId); + if ( event->m_messagingService) + event->m_messagingService->deleteOpId(event->opId); + if (event->getExceptionCode() == ExceptionCodes::None) + { + callbackManager->callOnSuccess(); + } + else + { + callbackManager->callOnError(); + } + } + else + { + callbackManager->callOnError(JSValueMakeUndefined(l_globalContext)); + } + +} +void MessagingController::OnAnswerReceived(const Api::Messaging::EventSendMessagePtr& event) +{ + LogDebug("ENTER"); + + JSValueRef error = NULL; + EventSendMessagePrivateDataPtr privateData = + DPL::StaticPointerCast(event->getPrivateData()); + Assert(NULL != privateData); + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = privateData->getCallbackManager(); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr recipientCallbackManager = privateData->getRecipientCallbackManager(); + + JSContextRef context = callbackManager->getContext(); + Assert(NULL != context); + + if (WrtDeviceApis::Commons::ExceptionCodes::None != event->getExceptionCode()) { + switch (event->getExceptionCode()) { + case WrtDeviceApis::Commons::ExceptionCodes::PlatformException: + case WrtDeviceApis::Commons::ExceptionCodes::ConversionException: + error = JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT); + default: + error = JSTizenExceptionFactory::makeErrorObject(context, + JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN); + } + } + + ConverterMessage converter(context); + JSValueRef recipient = converter.toJSValueRef(event->getRecipient()); + + //remove operation handle + if (event->m_messagingService) + { + LogDebug("Operation ID : " << event->opId); + event->m_messagingService->deleteOpId(event->opId); + } + if (WrtDeviceApis::Commons::ExceptionCodes::None == event->getExceptionCode()) { + LogDebug(" success size : " << event->m_successRecipients.size()); + + //JSObjectRef result = JSObjectMakeArray(context, event->m_successRecipients.size(), jsMessagingServiceObject, NULL); + std::vector successRecipentList; + + int cnt = event->m_successRecipients.size(); + LogDebug( "success count : " << cnt); + + + for(int index = 0; index < cnt; index++) + { + LogDebug( "success recipent : " << event->m_successRecipients[index]); + successRecipentList.push_back(converter.toJSValueRef(event->m_successRecipients[index])); + } + + JSObjectRef result = JSObjectMakeArray(context, cnt, successRecipentList.data(), NULL); + callbackManager->callOnSuccess(result); + + } + else { + //JSValueRef params[] = { error, recipient }; + //callbackManager->callOnError( params, sizeof(params) / sizeof(params[0])); + callbackManager->callOnError(error); + } + +#if 0 //old style code + if (!event->getSendCallbackPerRecipient()) { + //this is callback for whole operation, not single recipient + if (WrtDeviceApis::Commons::ExceptionCodes::None == event->getExceptionCode()) { + callbackManager->callOnSuccess(); + } else { + callbackManager->callOnError(error); + } + } else if (recipientCallbackManager) { + //this is callback for single recipient + ConverterMessage converter(context); + JSValueRef recipient = converter.toJSValueRef(event->getRecipient()); + if (WrtDeviceApis::Commons::ExceptionCodes::None == event->getExceptionCode()) { + recipientCallbackManager->callOnSuccess(recipient); + } else { + JSValueRef params[] = { error, recipient }; + recipientCallbackManager->callOnError( params, sizeof(params) / sizeof(params[0])); + } + } +#endif + +} + +} +} + diff --git a/src/standards/Tizen/Messaging/MessagingController.h b/src/standards/Tizen/Messaging/MessagingController.h new file mode 100755 index 0000000..01d83cc --- /dev/null +++ b/src/standards/Tizen/Messaging/MessagingController.h @@ -0,0 +1,68 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +/* + * @author sangtai kim(Sangtai.kim@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTPLUGINS_TIZEN_MESSAGING_CONTROLLER_H_ +#define WRTPLUGINS_TIZEN_MESSAGING_CONTROLLER_H_ + +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::Commons::EventAnswerReceiver GetMessagingServiceReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver MessagingServiceReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver SendMessageAnswerReceiver; + + +class MessagingController : + public SendMessageAnswerReceiver, + public GetMessagingServiceReceiver, + public MessagingServiceReceiver +{ + +public: + explicit MessagingController(); + virtual ~MessagingController(); + + static MessagingController& getInstance(); + +protected: + void OnAnswerReceived(const Api::Messaging::EventGetMessagingServicePtr &event); + + void OnAnswerReceived(const Api::Messaging::EventMessagingServicePtr &event); + + void OnAnswerReceived(const Api::Messaging::EventSendMessagePtr &event); + +}; + +typedef DPL::Singleton MessagingControllerSingleton; //for singleton + +} +} // WrtPlugins + +#endif //WRTPLUGINS_TIZEN_MESSAGING_CONTROLLER_H_ diff --git a/src/standards/Tizen/Messaging/MessagingErrorMsg.h b/src/standards/Tizen/Messaging/MessagingErrorMsg.h new file mode 100755 index 0000000..c32c65b --- /dev/null +++ b/src/standards/Tizen/Messaging/MessagingErrorMsg.h @@ -0,0 +1,31 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef _MESSAGING_ERROR_MESSAGE_H_ +#define _MESSAGING_ERROR_MESSAGE_H_ + +//exception message + +#define JSMESSAGING_EXCEPTION_MSG_UNKNOWN "UnknownError" +#define JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH "Type Mismatch" +#define JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT "Argument is invalid" +#define JSMESSAGING_EXCEPTION_MSG_IO "IO Error" +#define JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED "Not Supported" +#define JSMESSAGING_EXCEPTION_MSG_PERMISSION_DENIED "Permission Denied" +#define JSMESSAGING_EXCEPTION_MSG_NOT_FOUND "Not Found" + +#endif //_MESSAGING_ERROR_MESSAGE_H_ + diff --git a/src/standards/Tizen/Messaging/MessagingStorageMultiCallback.cpp b/src/standards/Tizen/Messaging/MessagingStorageMultiCallback.cpp new file mode 100755 index 0000000..49f2e97 --- /dev/null +++ b/src/standards/Tizen/Messaging/MessagingStorageMultiCallback.cpp @@ -0,0 +1,63 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#include "MessagingStorageMultiCallback.h" + + +namespace TizenApis { +namespace Tizen1_0 { + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +EventOnMessagingStorageChangesPrivateData::EventOnMessagingStorageChangesPrivateData( + const JSCallbackManagerPtr& messagesAdded, + const JSCallbackManagerPtr& messagesUpdated, + const JSCallbackManagerPtr& messagesRemoved, + const int functionIndex) : + m_messagesAdded(messagesAdded), + m_messagesUpdated(messagesUpdated), + m_messagesRemoved(messagesRemoved), + m_functionIndex(functionIndex), + m_filter(NULL) +{ +} + +int EventOnMessagingStorageChangesPrivateData::getFunctionIndex() const +{ + return m_functionIndex; +} + +JSCallbackManagerPtr EventOnMessagingStorageChangesPrivateData::getMessagesAdded() const +{ + return m_messagesAdded; +} + +JSCallbackManagerPtr EventOnMessagingStorageChangesPrivateData::getMessagesUpdated() const +{ + return m_messagesUpdated; +} + +JSCallbackManagerPtr EventOnMessagingStorageChangesPrivateData::getMessagesRemoved() const +{ + return m_messagesRemoved; +} + +} +} + + + + diff --git a/src/standards/Tizen/Messaging/MessagingStorageMultiCallback.h b/src/standards/Tizen/Messaging/MessagingStorageMultiCallback.h new file mode 100755 index 0000000..ea721f1 --- /dev/null +++ b/src/standards/Tizen/Messaging/MessagingStorageMultiCallback.h @@ -0,0 +1,90 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#ifndef TIZEN_MESSAGING_STORAGE_MULTI_CALLBACK_H_ +#define TIZEN_MESSAGING_STORAGE_MULTI_CALLBACK_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +struct OnMessagesChanged { + int functionIndex; + JSValueRef messagesAdded; + JSValueRef messagesUpdated; + JSValueRef messagesRemoved; + + OnMessagesChanged() + : + functionIndex(0), + messagesAdded(NULL), + messagesUpdated(NULL), + messagesRemoved(NULL) + { } +}; + +enum MessageFunctionNum{ + MESSAGES_MULTI_FUNCTION = 0, + CONVERSATIONS_MULTI_FUNCTION, + FOLDERS_MULTI_FUNCTION, + MESSAGING_MULTI_FUNTION_MAX +}; + +struct MessageFunctions { + const char *addedFunction; + const char *updatedFunction; + const char *removedFunction; +}; + +class EventOnMessagingStorageChangesPrivateData : public WrtDeviceApis::Commons::IEventPrivateData +{ + public: + EventOnMessagingStorageChangesPrivateData(const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr& messagesAdded, + const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr& messagesUpdated, + const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr& messagesRemoved, const int functionIndex); + + int getFunctionIndex() const; + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getMessagesAdded() const; + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getMessagesUpdated() const; + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getMessagesRemoved() const; + + void setFilter(const Api::Tizen::FilterPtr& filter) { + m_filter = filter; + } + + Api::Tizen::FilterPtr getFilter() { + return m_filter; + } + + +private: + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_messagesAdded; + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_messagesUpdated; + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_messagesRemoved; + int m_functionIndex; + Api::Tizen::FilterPtr m_filter; +}; + +typedef DPL::SharedPtr EventOnMessagingStorageChangesPrivateDataPtr; + +} +} + +#endif diff --git a/src/standards/Tizen/Messaging/config.xml b/src/standards/Tizen/Messaging/config.xml new file mode 100755 index 0000000..839d7c5 --- /dev/null +++ b/src/standards/Tizen/Messaging/config.xml @@ -0,0 +1,47 @@ + + + + libwrt-plugins-tizen-1.0-messaging.so + messaging.install.uri + SAMSUNG plugin group + SAMSUNG certificate authority + AAAABBBBCCCCDDDEEEE0000 + + + http://tizen.org/api/messaging + messaging.write + messaging.send + messaging.read + + + + + + + + + + + + + + + + + + + http://tizen.org/api/messaging.read + messaging.read + + + + http://tizen.org/api/messaging.send + messaging.send + + + + http://tizen.org/api/messaging.write + messaging.write + + + diff --git a/src/standards/Tizen/Messaging/plugin_config.cpp b/src/standards/Tizen/Messaging/plugin_config.cpp new file mode 100644 index 0000000..bb6e4c1 --- /dev/null +++ b/src/standards/Tizen/Messaging/plugin_config.cpp @@ -0,0 +1,337 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** +* @file plugin_config.cpp +* @author Kangsoo Lee (wpeter.lee@samsung.com) +* @version 0.1 +*/ + +#include +#include +#include +#include +#include +#include "plugin_config.h" + +#define MESSAGING_FEATURE_API "http://tizen.org/api/messaging" +#define MESSAGING_FEATURE_API_READ "http://tizen.org/api/messaging.read" +#define MESSAGING_FEATURE_API_SEND "http://tizen.org/api/messaging.send" +#define MESSAGING_FEATURE_API_WRITE "http://tizen.org/api/messaging.write" + +#define MESSAGING_DEVICE_CAP_READ "messaging.read" +#define MESSAGING_DEVICE_CAP_SEND "messaging.send" +#define MESSAGING_DEVICE_CAP_WRITE "messaging.write" + +namespace TizenApis { +namespace Tizen1_0 { + +using namespace WrtDeviceApis::Commons; + +const char* MessagingExportedNames[] = +{ + "getMessagingService", + "createMessage", + "sendMessage", + "loadMessageBody", + "loadMessageAttachment", + "sync", + "syncFolder", + "cancelOperation", + "findMessages", + "removeMessages", + "updateMessages", + "findConversations", + "removeConversations", + "findFolders", + "addMessagesChangeListener", + "addConversationsChangeListener", + "addFoldersChangeListener", + "removeChangeListener" +}; + +static WrtDeviceApis::Commons::FunctionMapping createMessagingFunctions(); +static WrtDeviceApis::Commons::FunctionMapping MessagingFunctions = createMessagingFunctions(); + +DEFINE_FUNCTION_GETTER(Messaging, MessagingFunctions); + +static WrtDeviceApis::Commons::FunctionMapping createMessagingFunctions() +{ + /** + * Device capabilities + */ + + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_MESSAGING_READ, MESSAGING_DEVICE_CAP_READ); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_MESSAGING_SEND, MESSAGING_DEVICE_CAP_SEND); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_MESSAGING_WRITE, MESSAGING_DEVICE_CAP_WRITE); + + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_MESSAGING_READ); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_MESSAGING_READ, DEVICE_CAP_MESSAGING_READ); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_MESSAGING_SEND); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_MESSAGING_SEND, DEVICE_CAP_MESSAGING_SEND); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_MESSAGING_WRITE); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_MESSAGING_WRITE, DEVICE_CAP_MESSAGING_WRITE); + + /** + * API features + */ + ACE_CREATE_FEATURE(FEATURE_MESSAGING, MESSAGING_FEATURE_API); + ACE_CREATE_FEATURE(FEATURE_MESSAGING_READ, MESSAGING_FEATURE_API_READ); + ACE_CREATE_FEATURE(FEATURE_MESSAGING_SEND, MESSAGING_FEATURE_API_SEND); + ACE_CREATE_FEATURE(FEATURE_MESSAGING_WRITE, MESSAGING_FEATURE_API_WRITE); + + ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE, FEATURE_MESSAGING); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE, FEATURE_MESSAGING_READ); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE, FEATURE_MESSAGING_SEND); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE, FEATURE_MESSAGING_WRITE); + + ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_READ); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ, FEATURE_MESSAGING); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ, FEATURE_MESSAGING_READ); + + ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_SEND); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_SEND, FEATURE_MESSAGING); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_SEND, FEATURE_MESSAGING_SEND); + + ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_WRITE); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_WRITE, FEATURE_MESSAGING); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_WRITE, FEATURE_MESSAGING_WRITE); +#if 0 + ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING, FEATURE_MESSAGING); + + ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_READ); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_READ, FEATURE_MESSAGING_READ); + + ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_SEND); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_SEND, FEATURE_MESSAGING_SEND); + + ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_WRITE); + ACE_ADD_API_FEATURE(MESSAGING_FEATURES_WRITE, FEATURE_MESSAGING_WRITE); +#endif + /** + * Functions + */ + + FunctionMapping MessagingFunctions; + + //get Message Service + AceFunction getMessagingServiceFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_GET_MESSAGING_SERVICE], + MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert(std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_GET_MESSAGING_SERVICE], + getMessagingServiceFunc)); + + /** Read **/ + AceFunction loadMessageBodyFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY], + MESSAGING_FEATURES_MESSAGING_READ, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY], + loadMessageBodyFunc)); + + AceFunction loadMessageAttachmentFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT], + MESSAGING_FEATURES_MESSAGING_READ, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT], + loadMessageAttachmentFunc)); + + AceFunction syncFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_SYNC], + MESSAGING_FEATURES_MESSAGING_READ, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_SYNC], + syncFunc)); + + AceFunction syncFolderFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_SYNC_FOLDER], + MESSAGING_FEATURES_MESSAGING_READ, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_SYNC_FOLDER], + syncFolderFunc)); + + AceFunction cancelOpFolderFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_CANCEL_OPERATION], + MESSAGING_FEATURES_MESSAGING_READ, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_CANCEL_OPERATION], + cancelOpFolderFunc)); + + AceFunction findMessagesFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_FIND_MESSAGES], + MESSAGING_FEATURES_MESSAGING_READ, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_FIND_MESSAGES], + findMessagesFunc)); + + AceFunction findConversationsFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_FIND_CONVERSATIONS], + MESSAGING_FEATURES_MESSAGING_READ, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_FIND_CONVERSATIONS], + findConversationsFunc)); + + AceFunction findFoldersFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_FIND_FOLDERS], + MESSAGING_FEATURES_MESSAGING_READ, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_FIND_FOLDERS], + findFoldersFunc)); + + AceFunction addMessagesChangeListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER], + MESSAGING_FEATURES_MESSAGING_READ, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER], + addMessagesChangeListenerFunc)); + + AceFunction addConversationsChangeListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER], + MESSAGING_FEATURES_MESSAGING_READ, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER], + addConversationsChangeListenerFunc)); + + AceFunction addFoldersChangeListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER], + MESSAGING_FEATURES_MESSAGING_READ, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER], + addFoldersChangeListenerFunc)); + + AceFunction removeChangeListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER], + MESSAGING_FEATURES_MESSAGING_READ, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER], + removeChangeListenerFunc)); + + + /** Send **/ + //create Message + AceFunction createMessageFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_CREATE_MESSAGE], + MESSAGING_FEATURES_MESSAGING_SEND, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_CREATE_MESSAGE], + createMessageFunc)); + + AceFunction sendMessageFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_SEND_MESSAGE], + MESSAGING_FEATURES_MESSAGING_SEND, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_SEND_MESSAGE], + sendMessageFunc)); + + /** Write **/ + AceFunction removeMessagesFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_REMOVE_MESSAGES], + MESSAGING_FEATURES_MESSAGING_WRITE, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_REMOVE_MESSAGES], + removeMessagesFunc)); + + AceFunction removeConversationsFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS], + MESSAGING_FEATURES_MESSAGING_WRITE, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS], + removeConversationsFunc)); + + AceFunction updateMessagesFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_MGR_SERVICE, + MessagingExportedNames[MESSAGING_FUNCTION_API_UPDATE_MESSAGES], + MESSAGING_FEATURES_MESSAGING_WRITE, + EMPTY_DEVICE_LIST); + + MessagingFunctions.insert( std::make_pair( + MessagingExportedNames[MESSAGING_FUNCTION_API_UPDATE_MESSAGES], + updateMessagesFunc)); + + return MessagingFunctions; +} + + +} +} + +#undef MESSAGING_FEATURE_API +#undef MESSAGING_FEATURE_API_READ +#undef MESSAGING_FEATURE_API_SEND +#undef MESSAGING_FEATURE_API_WRITE +#undef MESSAGING_DEVICE_CAP_READ +#undef MESSAGING_DEVICE_CAP_SEND +#undef MESSAGING_DEVICE_CAP_WRITE + diff --git a/src/standards/Tizen/Messaging/plugin_config.h b/src/standards/Tizen/Messaging/plugin_config.h new file mode 100644 index 0000000..ac6adb8 --- /dev/null +++ b/src/standards/Tizen/Messaging/plugin_config.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _MESSAGING_PLUGIN_CONFIG_H_ +#define _MESSAGING_PLUGIN_CONFIG_H_ + +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef enum +{ +MESSAGING_FUNCTION_API_GET_MESSAGING_SERVICE = 0, +MESSAGING_FUNCTION_API_CREATE_MESSAGE, +MESSAGING_FUNCTION_API_SEND_MESSAGE, +MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY, +MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT, +MESSAGING_FUNCTION_API_SYNC, +MESSAGING_FUNCTION_API_SYNC_FOLDER, +MESSAGING_FUNCTION_API_CANCEL_OPERATION, +MESSAGING_FUNCTION_API_FIND_MESSAGES, +MESSAGING_FUNCTION_API_REMOVE_MESSAGES, +MESSAGING_FUNCTION_API_UPDATE_MESSAGES, +MESSAGING_FUNCTION_API_FIND_CONVERSATIONS, +MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS, +MESSAGING_FUNCTION_API_FIND_FOLDERS, +MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER, +MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER, +MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER, +MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER +} MessagingFuncNames; + +extern const char* MessagingExportedNames[]; + +DECLARE_FUNCTION_GETTER(Messaging); + +#define MESSAGING_CHECK_ACCESS(globalContext, functionName) \ + aceCheckAccess >( \ + globalContext, \ + getMessagingFunctionData, \ + functionName) + +} +} + +#endif //MESSAGING_PLUGIN_CONFIG_H_ + diff --git a/src/standards/Tizen/Messaging/plugin_initializer.cpp b/src/standards/Tizen/Messaging/plugin_initializer.cpp new file mode 100755 index 0000000..51a88cf --- /dev/null +++ b/src/standards/Tizen/Messaging/plugin_initializer.cpp @@ -0,0 +1,51 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include +#include +#include "JSMessagingServiceManager.h" +#include "JSMessagingStorage.h" + +#define WRT_JS_EXTENSION_OBJECT_TIZEN "tizen" +#define OBJECT_MESSAGING ".messaging" + + +void on_widget_start_callback(int widgetId, JavaScriptContext context, const engine_interface_t *interface) { + LogDebug("[Tizen\\MessagingServiceManager] on_widget_start_callback ("< +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +class EventNFCChangedPrivateData : public WrtDeviceApis::Commons::IEventPrivateData +{ + public: + EventNFCChangedPrivateData(const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr& callbackManager, + const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr& detachedCallbackManager); + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getCallbackManager() const; + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getDetachedCallbackManager() const; + + private: + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_callbackManager; + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_detachedCallbackManager; +}; + +typedef DPL::SharedPtr EventNFCChangedPrivateDataPtr; +} +} + +#endif //TIZEN_NFC_EVENTNFCCHANGEDPRIVATE_H_ \ No newline at end of file diff --git a/src/standards/Tizen/NFC/JSNFCManager.cpp b/src/standards/Tizen/NFC/JSNFCManager.cpp new file mode 100755 index 0000000..7f9717c --- /dev/null +++ b/src/standards/Tizen/NFC/JSNFCManager.cpp @@ -0,0 +1,889 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "JSNFCManager.h" +#include "JSNdefMessage.h" +#include "JSNdefRecord.h" +#include "NFCConverter.h" +#include "NFCStaticController.h" +#include "EventNFCChangedPrivateData.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "plugin_config.h" + +using namespace std; +using namespace DPL; +using namespace TizenApis::Api::NFC; +using namespace TizenApis::Commons; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +#define TIZEN10_NFCMANAGER_ATTRIBUTENAME "NFCManager" + +#define TIZEN10_NFCMANAGER_TNF_EMPTY "NFC_RECORD_TNF_EMPTY" +#define TIZEN10_NFCMANAGER_TNF_WELL_KNOWN "NFC_RECORD_TNF_WELL_KNOWN" +#define TIZEN10_NFCMANAGER_TNF_MIME_MEDIA "NFC_RECORD_TNF_MIME_MEDIA" +#define TIZEN10_NFCMANAGER_TNF_URI "NFC_RECORD_TNF_URI" +#define TIZEN10_NFCMANAGER_TNF_EXTERNAL_RTD "NFC_RECORD_TNF_EXTERNAL_RTD" +#define TIZEN10_NFCMANAGER_TNF_UNKNOWN "NFC_RECORD_TNF_UNKNOWN" +#define TIZEN10_NFCMANAGER_TNF_UNCHANGED "NFC_RECORD_TNF_UNCHAGNED" + +namespace TizenApis { +namespace Tizen1_0 { + + JSClassDefinition JSNFCManager::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN10_NFCMANAGER_ATTRIBUTENAME, + 0, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSNFCManager::m_property[] = +{ + //NFCManagerProperties + {TIZEN10_NFCMANAGER_TNF_EMPTY, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN10_NFCMANAGER_TNF_WELL_KNOWN, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN10_NFCMANAGER_TNF_MIME_MEDIA, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN10_NFCMANAGER_TNF_URI, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN10_NFCMANAGER_TNF_EXTERNAL_RTD, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN10_NFCMANAGER_TNF_UNKNOWN, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN10_NFCMANAGER_TNF_UNCHANGED, getProperty, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSNFCManager::m_function[] = { + {"setTagListener", JSNFCManager::setTagListener, kJSPropertyAttributeNone }, + {"unsetTagListener", JSNFCManager::unsetTagListener, kJSPropertyAttributeNone}, + {"setPeerListener", JSNFCManager::setPeerListener, kJSPropertyAttributeNone }, + {"unsetPeerListener", JSNFCManager::unsetPeerListener, kJSPropertyAttributeNone}, + {"setNDEFListener", JSNFCManager::setNDEFListener, kJSPropertyAttributeNone }, + {"unsetNDEFListener", JSNFCManager::unsetNDEFListener, kJSPropertyAttributeNone}, + {"setSEEventListener", JSNFCManager::setSEEventListener, kJSPropertyAttributeNone }, + {"unsetSEEventListener", JSNFCManager::unsetSEEventListener, kJSPropertyAttributeNone}, + {"getCachedMessage", JSNFCManager::getCachedMessage, kJSPropertyAttributeNone}, + {"createNDEFMessage", JSNFCManager::createNDEFMessage, kJSPropertyAttributeNone}, + {"createNDEFMessageFromRawData", JSNFCManager::createNDEFMessageFromRawData, kJSPropertyAttributeNone}, + {"createNDEFRecord", JSNFCManager::createNDEFRecord, kJSPropertyAttributeNone}, + {"createNDEFRecordText", JSNFCManager::createNDEFRecordText, kJSPropertyAttributeNone}, + {"createNDEFRecordURI", JSNFCManager::createNDEFRecordURI, kJSPropertyAttributeNone}, + {"createNDEFRecordMedia", JSNFCManager::createNDEFRecordMedia, kJSPropertyAttributeNone}, + { 0, 0, 0} +}; + +JSClassRef JSNFCManager::m_jsClassRef = JSClassCreate(JSNFCManager::getClassInfo()); + +void JSNFCManager::initialize(JSContextRef context, JSObjectRef object) +{ + NFCManagerPrivObject* priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + Try { + INFCManagerPtr NFCManager( NFCFactory::getInstance().createNFCManagerObject() ); + priv = new NFCManagerPrivObject(context, NFCManager); + if(!JSObjectSetPrivate(object, static_cast(priv))) { + LogError("Object can't store private data."); + delete priv; + } + } Catch (UnsupportedException) { + LogError("UnsupportedException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + } +} + +void JSNFCManager::finalize(JSObjectRef object) +{ + LogDebug( "entered" ); + NFCManagerPrivObject *priv = static_cast( JSObjectGetPrivate( object ) ) ; + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting NFC Manager object"); + delete priv; +} + + +const JSClassRef JSNFCManager::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNFCManager::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSNFCManager::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("Enter"); + + Try { + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NFCMANAGER_TNF_EMPTY)) { + return convert.toJSValueRef(NFC_TNF_EMPTY); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NFCMANAGER_TNF_WELL_KNOWN)) { + return convert.toJSValueRef(NFC_TNF_WELL_KNOWN); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NFCMANAGER_TNF_MIME_MEDIA)) { + return convert.toJSValueRef(NFC_TNF_MIME_MEDIA); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NFCMANAGER_TNF_URI)) { + return convert.toJSValueRef(NFC_TNF_URI); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NFCMANAGER_TNF_EXTERNAL_RTD)) { + return convert.toJSValueRef(NFC_TNF_EXTERNAL_RTD); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NFCMANAGER_TNF_UNKNOWN)) { + return convert.toJSValueRef(NFC_TNF_UNKNOWN); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NFCMANAGER_TNF_UNCHANGED)) { + return convert.toJSValueRef(NFC_TNF_UNCHAGNED); + } + } Catch (ConversionException) { + LogError("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCManager::setTagListener (JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) { + LogDebug("JSNFCManager::setTagListener Enter"); + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + JSContextRef global_context = privateObject->getContext(); + NFCConverter nfcConverter(context); + Validator validator(context, exception); + + AceSecurityStatus status = NFC_CHECK_ACCESS(global_context, NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount == 0) { + /* Argument count must be 1, 2 or 3. */ + LogError("JSNFCManager::setTagListener TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) ) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCManager::setTagListener TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if (argumentCount > 1) { + if (!JSValueIsNull(context, arguments[1]) && !validator.isCallback(arguments[1])) { + /* 2nd argument must be Callback. */ + LogError("JSNFCManager::setTagListener TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + } + + JSValueRef onErrorForCbm = NULL; + NFCChangedCallback callbacks; + + if (JSValueIsObject(context, arguments[0]) && + !validator.isCallback(arguments[0])) { + callbacks = nfcConverter.toNFCChangedCallback(arguments[0]); + } else { + LogError("DetectedCB must has onAttach and onDetach"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (argumentCount > 1) { + if (validator.isCallback(arguments[1])) { + onErrorForCbm = arguments[1]; + } + } + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(global_context, callbacks.onAttach, onErrorForCbm, true, true); + JSCallbackManagerPtr detachedCallbackManager = JSCallbackManager::createObject(global_context, callbacks.onDetach, NULL); + + Try { + INFCManagerPtr NFC_ptr( privateObject->getObject() ); + + //process the filter object + TagFilterPtr tagFilter; + if ((argumentCount > 2) && !JSValueIsNull(context, arguments[2])) { + if (!JSValueIsNull(context, arguments[2]) && + !JSValueIsUndefined(context, arguments[2]) && + JSIsArrayValue(context, arguments[2])) { + tagFilter = nfcConverter.toNFCTagFilter(arguments[2]); + + } else + Throw(ConversionException); + } + else + { + TagFilterPtr _filter (new TagFilter()); + tagFilter = _filter; + } + + EventNFCChangedPrivateDataPtr privateData( + new EventNFCChangedPrivateData(callbackManager, + detachedCallbackManager) + ); + EventNFCChangedEmitterPtr emitter(new EventNFCChangedEmitter); + emitter->setListener(&NFCStaticController::getInstance()); + emitter->setEventPrivateData(StaticPointerCast(privateData)); + + if (NFC_ptr->setTagListener(emitter, tagFilter, (void *)privateObject) != 0) + Throw(PlatformException); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::setTagListener : ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::setTagListener InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCManager::setPeerListener (JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) { + LogDebug("JSNFCManager::setPeerListener Enter"); + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + JSContextRef global_context = privateObject->getContext(); + NFCConverter nfcConverter(context); + Validator validator(context, exception); + + AceSecurityStatus status = NFC_CHECK_ACCESS(global_context, NFC_FUNCTION_API_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount == 0) { + /* Argument count must be 1, 2 or 3. */ + LogError("JSNFCManager::setPeerListener TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) ) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCManager::setPeerListener TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if (argumentCount > 1) { + if (!JSValueIsNull(context, arguments[1]) && !validator.isCallback(arguments[1])) { + /* 2nd argument must be Callback. */ + LogError("JSNFCManager::setPeerListener TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + } + + JSValueRef onErrorForCbm = NULL; + NFCChangedCallback callbacks; + + if (JSValueIsObject(context, arguments[0]) && + !validator.isCallback(arguments[0])) { + callbacks = nfcConverter.toNFCChangedCallback(arguments[0]); + } else { + LogError("DetectedCB must has onAttach and onDetach"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (argumentCount > 1) { + if (validator.isCallback(arguments[1])) { + onErrorForCbm = arguments[1]; + } + } + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(global_context, callbacks.onAttach, onErrorForCbm, true, true); + JSCallbackManagerPtr detachedCallbackManager = JSCallbackManager::createObject(global_context, callbacks.onDetach, NULL); + + Try { + INFCManagerPtr NFC_ptr( privateObject->getObject() ); + + EventNFCChangedPrivateDataPtr privateData( + new EventNFCChangedPrivateData(callbackManager, + detachedCallbackManager) + ); + + EventNFCChangedEmitterPtr emitter(new EventNFCChangedEmitter); + emitter->setListener(&NFCStaticController::getInstance()); + emitter->setEventPrivateData(StaticPointerCast(privateData)); + + if (NFC_ptr->setPeerListener(emitter, (void *)privateObject) != 0) + Throw(PlatformException); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::setPeerListener : ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::setPeerListener InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCManager::setNDEFListener (JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) { + LogDebug("JSNFCManager::setNDEFListener Enter"); + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + JSContextRef global_context = privateObject->getContext(); + Validator validator(context, exception); + + AceSecurityStatus status = NFC_CHECK_ACCESS(global_context, NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount == 0) { + /* Argument count must be 1 or 2. */ + LogError("JSNFCManager::setNDEFListener TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !validator.isCallback(arguments[0])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCManager::setNDEFListener TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if (argumentCount > 1) { + if (!JSValueIsNull(context, arguments[1]) && !validator.isCallback(arguments[1])) { + /* 2nd argument must be Callback. */ + LogError("JSNFCManager::setNDEFListener TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[0])) { + onSuccessForCbm = arguments[0]; + } + if (argumentCount > 1) { + if (validator.isCallback(arguments[1])) { + onErrorForCbm = arguments[1]; + } + } + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(global_context, onSuccessForCbm, onErrorForCbm, true, true); + + Try { + INFCManagerPtr NFC_ptr( privateObject->getObject() ); + + EventNFCChangedNdefEmitterPtr emitter(new EventNFCChangedNdefEmitter); + emitter->setListener(&NFCStaticController::getInstance()); + emitter->setEventPrivateData(StaticPointerCast(callbackManager)); + + if (NFC_ptr->setNDEFListener(emitter) != 0) + Throw(PlatformException); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::setNDEFListener : ConversionException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::setNDEFListener InvalidArgumentException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCManager::setSEEventListener (JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) { + LogDebug("JSNFCManager::setSEEventListener Enter"); + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + JSContextRef global_context = privateObject->getContext(); + Validator validator(context, exception); + + AceSecurityStatus status = NFC_CHECK_ACCESS(global_context, NFC_FUNCTION_API_SE_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount == 0) { + /* Argument count must be 1 or 2. */ + LogError("JSNFCManager::setSEEventListener TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !validator.isCallback(arguments[0])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCManager::setSEEventListener TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if (argumentCount > 1) { + if (!JSValueIsNull(context, arguments[1]) && !validator.isCallback(arguments[1])) { + /* 2nd argument must be Callback. */ + LogError("JSNFCManager::setSEEventListener TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[0])) { + onSuccessForCbm = arguments[0]; + } + if (argumentCount > 1) { + if (validator.isCallback(arguments[1])) { + onErrorForCbm = arguments[1]; + } + } + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(global_context, onSuccessForCbm, onErrorForCbm, true, true); + + Try { + INFCManagerPtr NFC_ptr( privateObject->getObject() ); + + EventNFCChangedSeEventEmitterPtr emitter(new EventNFCChangedSeEventEmitter); + emitter->setListener(&NFCStaticController::getInstance()); + emitter->setEventPrivateData(StaticPointerCast(callbackManager)); + + if (NFC_ptr->setSEEventListener(emitter) != 0) + Throw(PlatformException); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::setSEEventListener : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::TYPE_MISMATCH_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::setSEEventListener InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCManager::unsetTagListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { + LogDebug("JSNFCManager::unsetNFCTagListener Enter"); + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try { + INFCManagerPtr NFCs( privateObject->getObject() ); + + NFCs->unsetTagListener(); + return JSValueMakeUndefined(context); + } Catch (NullPointerException) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCManager::unsetPeerListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { + LogDebug("JSNFCManager::unsetPeerListener Enter"); + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try { + INFCManagerPtr NFCs( privateObject->getObject() ); + + NFCs->unsetPeerListener(); + return JSValueMakeUndefined(context); + } Catch (NullPointerException) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCManager::unsetNDEFListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { + LogDebug("JSNFCManager::unsetNDEFListener Enter"); + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try { + INFCManagerPtr NFCs( privateObject->getObject() ); + + NFCs->unsetNDEFListener(); + return JSValueMakeUndefined(context); + } Catch (NullPointerException) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCManager::unsetSEEventListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { + LogDebug("JSNFCManager::unsetSEEventListener Enter"); + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_SE_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try { + INFCManagerPtr NFCs( privateObject->getObject() ); + + NFCs->unsetSEEventListener(); + return JSValueMakeUndefined(context); + } Catch (NullPointerException) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCManager::getCachedMessage (JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) { + LogDebug("JSNFCManager::getCachedMessage Enter"); + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + JSContextRef global_context = privateObject->getContext(); + + AceSecurityStatus status = NFC_CHECK_ACCESS(global_context, NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + +Try { + INFCManagerPtr NFC_ptr( privateObject->getObject() ); + void *cachedMessage = NFC_ptr->getCachedMessage(); + if (cachedMessage != NULL) + return JSNdefMessage::createJSObject(global_context, NFC_ptr->getCachedMessage()); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCManager::createNDEFMessage(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered "); + Try { + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + INFCManagerPtr NFCManager(privateObject->getObject()); + NFCConverter convert(context); + + if ((argumentCount < 1) || JSValueIsNull(context, arguments[0])) { + LogError("NdefRecordArray parameter is JSNull/JSUndefined/Not Number"); + return JSNdefMessage::createJSObject(privateObject->getContext()); + } else if ((JSValueIsUndefined(context, arguments[0]) || !JSIsArrayValue(context, arguments[0]))) { + Throw(ConversionException); + } + + return JSNdefMessage::createJSObject(privateObject->getContext(), convert.toVectorOfRecordHandles(arguments[0])); + } Catch(ConversionException) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCManager::createNDEFMessageFromRawData(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered "); + Try { + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + INFCManagerPtr NFCManager(privateObject->getObject()); + NFCConverter convert(context); + + if ((argumentCount < 1) || JSValueIsNull(context, arguments[0])) { + LogError("NdefRecordArray parameter is JSNull/JSUndefined/Not Number"); + return JSNdefMessage::createJSObject(privateObject->getContext()); + } else if ((JSValueIsUndefined(context, arguments[0]) || !JSIsArrayValue(context, arguments[0]))) { + Throw(ConversionException); + } + + return JSNdefMessage::createJSObject(privateObject->getContext(), convert.toVectorOfUChars(arguments[0])); + } Catch(ConversionException) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCManager::createNDEFRecord(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered "); + Try { + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + INFCManagerPtr NFCManager(privateObject->getObject()); + NFCConverter convert(context); + + if ((argumentCount < 2) || (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0])) + || (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !JSIsArrayValue(context, arguments[1]))) { + LogError("parameter is JSNull/JSUndefined/Not array"); + Throw(ConversionException); + } + + return JSNdefRecord::createJSObject(privateObject->getContext(), convert.toNdefRecordProperties(arguments[0], exception), convert.toVectorOfUChars(arguments[1])); + } Catch(ConversionException) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCManager::createNDEFRecordText(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered "); + Try { + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + INFCManagerPtr NFCManager(privateObject->getObject()); + NFCConverter convert(context); + + if ((argumentCount < 2) || (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsString(context, arguments[0])) + || (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !JSValueIsString(context, arguments[1]))) { + LogError("parameter is JSNull/JSUndefined/Not array"); + Throw(ConversionException); + } + + short encodeType = NFC_TEXT_ENCODE_UTF_8; + + if ((argumentCount > 2) && (!JSValueIsNull(context, arguments[2]))) { + if (JSValueIsUndefined(context, arguments[2]) || !JSValueIsString(context, arguments[2])) + Throw(ConversionException); + encodeType = convert.toNfcTextEncodeUTF(convert.toString(arguments[2])); + } + + return JSNdefRecord::createJSObject(privateObject->getContext(), convert.toString(arguments[0]), convert.toString(arguments[1]), encodeType); + } Catch(ConversionException) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCManager::createNDEFRecordURI(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered "); + Try { + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + INFCManagerPtr NFCManager(privateObject->getObject()); + NFCConverter convert(context); + + if ((argumentCount < 1) || (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsString(context, arguments[0]))) { + LogError("parameter is JSNull/JSUndefined/Not array"); + Throw(ConversionException); + } + + return JSNdefRecord::createJSObject(privateObject->getContext(), convert.toString(arguments[0])); + } Catch(ConversionException) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCManager::createNDEFRecordMedia(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered "); + Try { + NFCManagerPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + INFCManagerPtr NFCManager(privateObject->getObject()); + NFCConverter convert(context); + + if ((argumentCount < 2) || (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsString(context, arguments[0])) + || (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !JSIsArrayValue(context, arguments[1]))) { + LogError("parameter is JSNull/JSUndefined/Not array"); + Throw(InvalidArgumentException); + } + + return JSNdefRecord::createJSObject(privateObject->getContext(), convert.toString(arguments[0]), convert.toVectorOfUChars(arguments[1])); + } Catch(ConversionException) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +} +} diff --git a/src/standards/Tizen/NFC/JSNFCManager.h b/src/standards/Tizen/NFC/JSNFCManager.h new file mode 100755 index 0000000..bd484d0 --- /dev/null +++ b/src/standards/Tizen/NFC/JSNFCManager.h @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _JS_TIZEN_NFCMANAGER_H_ +#define _JS_TIZEN_NFCMANAGER_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject NFCManagerPrivObject; + +class JSNFCManager +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Getters for properties + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + /** + * register a listener to watch NFC tag. + */ + static JSValueRef setTagListener(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + /** + * deregister the listener which was registered by using setTagListener api. + */ + static JSValueRef unsetTagListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + /** + * register a listener to watch NFC tag. + */ + static JSValueRef setPeerListener(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + /** + * deregister the listener which was registered by using setTagListener api. + */ + static JSValueRef unsetPeerListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + /** + * register a listener to watch NFC tag. + */ + static JSValueRef setNDEFListener(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + /** + * deregister the listener which was registered by using setTagListener api. + */ + static JSValueRef unsetNDEFListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + /** + * register a listener to watch NFC SE Event. + */ + static JSValueRef setSEEventListener(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + /** + * deregister the listener which was registered by using setSEEventListener api. + */ + static JSValueRef unsetSEEventListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef getCachedMessage(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef createNDEFMessage(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef createNDEFMessageFromRawData(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef createNDEFRecord(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef createNDEFRecordText(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef createNDEFRecordURI(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef createNDEFRecordMedia(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +} +} + +#endif /* _JS_TIZEN_NFCMANAGER_H_ */ diff --git a/src/standards/Tizen/NFC/JSNFCTag.cpp b/src/standards/Tizen/NFC/JSNFCTag.cpp new file mode 100755 index 0000000..70619ff --- /dev/null +++ b/src/standards/Tizen/NFC/JSNFCTag.cpp @@ -0,0 +1,492 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "JSNFCTag.h" +#include "JSNdefMessage.h" +#include "JSNFCManager.h" +#include "NFCConverter.h" +#include "ResponseDispatcher.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "plugin_config.h" + + +using namespace TizenApis::Api::NFC; +using namespace TizenApis::Commons; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DPL; + +#define TIZEN10_NFCTAG_ATTRIBUTENAME "NFCTag" + +#define TIZEN10_NFCTAG_TYPE "type" +#define TIZEN10_NFCTAG_ISSUPPORTEDNDEF "isSupportedNDEF" +#define TIZEN10_NFCTAG_NDEFSIZE "ndefSize" +#define TIZEN10_NFCTAG_PROPERTIES "properties" +#define TIZEN10_NFCTAG_ISCONNECTED "isConnected" + +namespace TizenApis { +namespace Tizen1_0 { + + JSClassDefinition JSNFCTag::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN10_NFCTAG_ATTRIBUTENAME, + 0, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSNFCTag::m_property[] = +{ + //NFCTagProperties + { TIZEN10_NFCTAG_TYPE, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { TIZEN10_NFCTAG_ISSUPPORTEDNDEF, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { TIZEN10_NFCTAG_NDEFSIZE, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { TIZEN10_NFCTAG_PROPERTIES, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { TIZEN10_NFCTAG_ISCONNECTED, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSNFCTag::m_function[] = { + {"readNDEF", JSNFCTag::readNDEF, kJSPropertyAttributeNone}, + {"writeNDEF", JSNFCTag::writeNDEF, kJSPropertyAttributeNone}, + {"transceive", JSNFCTag::transceive, kJSPropertyAttributeNone}, + {"formatNDEF", JSNFCTag::formatNDEF, kJSPropertyAttributeNone}, + { 0, 0, 0} +}; + +JSClassRef JSNFCTag::m_jsClassRef = JSClassCreate(JSNFCTag::getClassInfo()); + +JSObjectRef JSNFCTag::createJSObject(JSContextRef context, void *tagHandle, void* privManager) { + LogDebug("entered"); + + INFCTagPtr NFCTag = NFCFactory::getInstance().createNFCTagObject(tagHandle); + NFCTag->setPrivateNFCManagerPtr(privManager); + + NFCTagPrivObject *priv = new NFCTagPrivObject(context, NFCTag); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NFCTag object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + +void JSNFCTag::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSNFCTag::finalize(JSObjectRef object) +{ + LogDebug( "entered" ); + NFCTagPrivObject *priv = static_cast( JSObjectGetPrivate( object ) ) ; + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting timezone object"); + delete priv; +} + + +const JSClassRef JSNFCTag::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNFCTag::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSNFCTag::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("Enter"); + + Try { + NFCTagPrivObject* privateObject = static_cast(JSObjectGetPrivate(object)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + INFCTagPtr NFCTag(privateObject->getObject()); + NFCConverter convert(context); + + LogDebug("propertyName : " << convert.toString(propertyName)); + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NFCTAG_TYPE)) { + return convert.toJSValueRef(convert.toNfcTagTypeString(NFCTag->getTagType())); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NFCTAG_ISSUPPORTEDNDEF)) { + return convert.toJSValueRef(NFCTag->isNDEFSupport()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NFCTAG_NDEFSIZE)) { + return convert.toJSValueRefLong(NFCTag->getNdefSize()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NFCTAG_PROPERTIES)) { + LogDebug("get Properties"); + return convert.toJSValueRef(NFCTag->getProperties()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NFCTAG_ISCONNECTED)) { + NFCManagerPrivObject* privateNFCManager = static_cast(NFCTag->getPrivateNFCManagerPtr()); + if (!privateNFCManager) { + LogError("NFC Manager Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + INFCManagerPtr NFCManager(privateNFCManager->getObject()); + return convert.toJSValueRef(NFCManager->isValidHandle(NFCTag->getHandle())); + } + } Catch (ConversionException) { + LogError("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCTag::readNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTagPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Validator validator(context, exception); + + if (argumentCount < 1) { + LogError("JSNFCTag::readNDEF TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !validator.isCallback(arguments[0])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTag::readNDEF TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 1) && !JSValueIsNull(context, arguments[1])) { + if (JSValueIsUndefined(context, arguments[1]) || !validator.isCallback(arguments[1])) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTag::readNDEF TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[0])) { + onSuccessForCbm = arguments[0]; + } + if (argumentCount > 1) { + if (validator.isCallback(arguments[1])) { + onErrorForCbm = arguments[1]; + } + } + + INFCTagPtr NFCTag(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagActionReadPtr event(new EventTagActionRead()); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + + NFCTag->readNdef(event); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::readNDEF : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::readNDEF InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCTag::writeNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTagPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 2 ) { + LogError("JSNFCTag::writeNdef TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !validator.isCallback(arguments[1])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTag::writeNdef TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 2) && (!JSValueIsNull(context, arguments[2]) && (JSValueIsUndefined(context, arguments[2]) || !validator.isCallback(arguments[2])))) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTag::writeNdef TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[1])) { + onSuccessForCbm = arguments[1]; + } + + if ((argumentCount > 2) && (validator.isCallback(arguments[2]))) { + onErrorForCbm = arguments[2]; + } + + void *messageHandle = convert.getMessageHandle(arguments[0]); + + INFCTagPtr NFCTag(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagActionWritePtr event(new EventTagActionWrite()); + event->writeNdef(messageHandle); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTag->writeNdef(event); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::writeNDEF : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::writeNDEF InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCTag::transceive(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTagPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 2 ) { + LogError("JSNFCTag::transceive TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSIsArrayValue(context, arguments[0])) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTag::transceive TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !validator.isCallback(arguments[1])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTag::transceive TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 2) && (!JSValueIsNull(context, arguments[2]) && (JSValueIsUndefined(context, arguments[2]) || !validator.isCallback(arguments[2])))) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTag::transceive TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + std::vector data = convert.toVectorOfUChars(arguments[0]); + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[1])) { + onSuccessForCbm = arguments[1]; + } + + if ((argumentCount > 2) && (validator.isCallback(arguments[2]))) { + onErrorForCbm = arguments[2]; + } + + INFCTagPtr NFCTag(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagActionTransceivePtr event(new EventTagActionTransceive()); + event->transceive(data); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTag->transceive(event); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::transceive : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::transceive InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCTag::formatNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTagPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 1) { + LogError("JSNFCTag::formatNDEF TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !validator.isCallback(arguments[0])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTag::formatNDEF TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 1) && !JSValueIsNull(context, arguments[1]) && (JSValueIsUndefined(context, arguments[1]) || !validator.isCallback(arguments[1]))) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTag::formatNDEF TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[0])) { + onSuccessForCbm = arguments[0]; + } + + if ((argumentCount > 1) && (validator.isCallback(arguments[1]))) { + onErrorForCbm = arguments[1]; + } + + std::vector key; + if ((argumentCount > 2) && !JSValueIsNull(context, arguments[2])){ + if (JSValueIsUndefined(context, arguments[2]) || !JSIsArrayValue(context, arguments[2])) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTag::formatNDEF TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + key = convert.toVectorOfUChars(arguments[2]); + } + + INFCTagPtr NFCTag(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagActionFormatPtr event(new EventTagActionFormat()); + event->format(key); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTag->format(event); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::formatNDEF : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::formatNDEF InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +} +} diff --git a/src/standards/Tizen/NFC/JSNFCTag.h b/src/standards/Tizen/NFC/JSNFCTag.h new file mode 100755 index 0000000..adc2caa --- /dev/null +++ b/src/standards/Tizen/NFC/JSNFCTag.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _JS_TIZEN_NFCTAG_H_ +#define _JS_TIZEN_NFCTAG_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject NFCTagPrivObject; + +class JSNFCTag +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, void *tagHandle, void* privManager); + +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Getters for properties + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + static JSValueRef readNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef writeNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef transceive(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef formatNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +} +} + +#endif /* _JS_TIZEN_NFCTAG_H_ */ diff --git a/src/standards/Tizen/NFC/JSNFCTagMifareClassic.cpp b/src/standards/Tizen/NFC/JSNFCTagMifareClassic.cpp new file mode 100755 index 0000000..89fd2a3 --- /dev/null +++ b/src/standards/Tizen/NFC/JSNFCTagMifareClassic.cpp @@ -0,0 +1,731 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "JSNFCTagMifareClassic.h" +#include "NFCConverter.h" +#include "ResponseDispatcher.h" +#include "JSNFCTag.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "plugin_config.h" + + +using namespace TizenApis::Api::NFC; +using namespace TizenApis::Commons; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DPL; + +#define TIZEN10_NFCTTAGMIFARECLASSIC_ATTRIBUTENAME "NFCTagMifareClassic" + +namespace TizenApis { +namespace Tizen1_0 { + + JSClassDefinition JSNFCTagMifareClassic::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN10_NFCTTAGMIFARECLASSIC_ATTRIBUTENAME, + JSNFCTag::getClassRef(), + NULL, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticFunction JSNFCTagMifareClassic::m_function[] = { + {"authenticateWithKeyA", JSNFCTagMifareClassic::authenticateWithKeyA, kJSPropertyAttributeNone}, + {"authenticateWithKeyB", JSNFCTagMifareClassic::authenticateWithKeyB, kJSPropertyAttributeNone}, + {"readBlock", JSNFCTagMifareClassic::readBlock, kJSPropertyAttributeNone}, + {"writeBlock", JSNFCTagMifareClassic::writeBlock, kJSPropertyAttributeNone}, + {"incrementBlockValue", JSNFCTagMifareClassic::incrementBlockValue, kJSPropertyAttributeNone}, + {"decrementBlockValue", JSNFCTagMifareClassic::decrementBlockValue, kJSPropertyAttributeNone}, + {"transfer", JSNFCTagMifareClassic::transfer, kJSPropertyAttributeNone}, + {"restore", JSNFCTagMifareClassic::restore, kJSPropertyAttributeNone}, + { 0, 0, 0} +}; + +JSClassRef JSNFCTagMifareClassic::m_jsClassRef = JSClassCreate(JSNFCTagMifareClassic::getClassInfo()); + +JSObjectRef JSNFCTagMifareClassic::createJSObject(JSContextRef context, void *tagHandle, void* privManager) { + LogDebug("entered"); + + INFCTagMifareClassicPtr NFCTagMifareClassic = NFCFactory::getInstance().createNFCTagMifareClassicObject(tagHandle); + NFCTagMifareClassic->setPrivateNFCManagerPtr(privManager); + + NFCTagMifareClassicPrivObject *priv = new NFCTagMifareClassicPrivObject(context, NFCTagMifareClassic); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NFCTagMifareClassic object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + +void JSNFCTagMifareClassic::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSNFCTagMifareClassic::finalize(JSObjectRef object) +{ + LogDebug( "entered" ); + NFCTagMifareClassicPrivObject *priv = static_cast( JSObjectGetPrivate( object ) ) ; + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting timezone object"); + delete priv; +} + + +const JSClassRef JSNFCTagMifareClassic::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNFCTagMifareClassic::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSNFCTagMifareClassic::authenticateWithKeyA(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTagMifareClassicPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 3) { + LogError("JSNFCTagMifareClassic::authenticateWithKeyA TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if ((JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSIsArrayValue(context, arguments[0])) + || (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !JSValueIsNumber(context, arguments[1]))){ + LogError("JSNFCTagMifareClassic::authenticateWithKeyA TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[2]) || JSValueIsUndefined(context, arguments[2]) || !validator.isCallback(arguments[2])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTagMifareClassic::authenticateWithKeyA TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if((argumentCount > 3) && !JSValueIsNull(context, arguments[3]) && (JSValueIsUndefined(context, arguments[3]) || !validator.isCallback(arguments[3]))) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTagMifareClassic::authenticateWithKeyA TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[2])) { + onSuccessForCbm = arguments[2]; + } + if ((argumentCount > 3) && (validator.isCallback(arguments[3]))) { + onErrorForCbm = arguments[3]; + } + + + INFCTagMifareClassicPtr NFCTagMifareClassic(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagMifareClassicAuthenticateWithKeyAPtr event(new EventTagMifareClassicAuthenticateWithKeyA(convert.toVectorOfUChars(arguments[0]), convert.toInt(arguments[1]))); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTagMifareClassic->authenticateWithKeyA(event); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::authenticateWithKeyA : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::authenticateWithKeyA InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCTagMifareClassic::authenticateWithKeyB(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTagMifareClassicPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 3) { + LogError("JSNFCTagMifareClassic::authenticateWithKeyB TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if ((JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSIsArrayValue(context, arguments[0])) + || (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !JSValueIsNumber(context, arguments[1]))){ + LogError("JSNFCTagMifareClassic::authenticateWithKeyB TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[2]) || JSValueIsUndefined(context, arguments[2]) || !validator.isCallback(arguments[2])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTagMifareClassic::authenticateWithKeyB TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if((argumentCount > 3) && !JSValueIsNull(context, arguments[3]) && (JSValueIsUndefined(context, arguments[3]) || !validator.isCallback(arguments[3]))){ + /* 2nd argument must be Callback. */ + LogError("JSNFCTagMifareClassic::authenticateWithKeyB TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[2])) { + onSuccessForCbm = arguments[2]; + } + if ((argumentCount > 3) && validator.isCallback(arguments[3])) { + onErrorForCbm = arguments[3]; + } + + + INFCTagMifareClassicPtr NFCTagMifareClassic(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagMifareClassicAuthenticateWithKeyBPtr event(new EventTagMifareClassicAuthenticateWithKeyB(convert.toVectorOfUChars(arguments[0]), convert.toInt(arguments[1]))); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTagMifareClassic->authenticateWithKeyB(event); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::authenticateWithKeyB : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::authenticateWithKeyB InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCTagMifareClassic::readBlock(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTagMifareClassicPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 2) { + LogError("JSNFCTagMifareClassic::readBlock TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsNumber(context, arguments[0])) { + LogError("JSNFCTagMifareClassic::readBlock TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !validator.isCallback(arguments[1])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTagMifareClassic::readBlock TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 2) && !JSValueIsNull(context, arguments[2]) && (JSValueIsUndefined(context, arguments[2]) || !validator.isCallback(arguments[2]))) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTagMifareClassic::readBlock TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[1])) { + onSuccessForCbm = arguments[1]; + } + if ((argumentCount > 2) && (validator.isCallback(arguments[2]))) { + onErrorForCbm = arguments[2]; + } + + + INFCTagMifareClassicPtr NFCTagMifareClassic(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagMifareClassicReadBlockPtr event(new EventTagMifareClassicReadBlock(convert.toInt(arguments[0]))); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTagMifareClassic->readBlock(event); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::readBlock : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::readBlock InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCTagMifareClassic::writeBlock(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTagMifareClassicPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 3) { + LogError("JSNFCTagMifareClassic::writeBlock TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if ((JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsNumber(context, arguments[0])) + || (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !JSIsArrayValue(context, arguments[1]))){ + LogError("JSNFCTagMifareClassic::writeBlock TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[2]) || JSValueIsUndefined(context, arguments[2]) || !validator.isCallback(arguments[2])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTagMifareClassic::writeBlock TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 3) && !JSValueIsNull(context, arguments[3]) && (JSValueIsUndefined(context, arguments[3]) || !validator.isCallback(arguments[3]))) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTagMifareClassic::writeBlock TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[2])) { + onSuccessForCbm = arguments[2]; + } + if ((argumentCount > 3) && (validator.isCallback(arguments[3]))) { + onErrorForCbm = arguments[3]; + } + + + INFCTagMifareClassicPtr NFCTagMifareClassic(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagMifareClassicWriteBlockPtr event(new EventTagMifareClassicWriteBlock(convert.toInt(arguments[0]), convert.toVectorOfUChars(arguments[1]))); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTagMifareClassic->writeBlock(event); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::writeBlock : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::writeBlock InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCTagMifareClassic::incrementBlockValue(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTagMifareClassicPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 3) { + LogError("JSNFCTagMifareClassic::incrementBlockValue TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if ((JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsNumber(context, arguments[0])) + || (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !JSValueIsNumber(context, arguments[1]))){ + LogError("JSNFCTagMifareClassic::incrementBlockValue TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[2]) || JSValueIsUndefined(context, arguments[2]) || !validator.isCallback(arguments[2])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTagMifareClassic::incrementBlockValue TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 3) && !JSValueIsNull(context, arguments[3]) && (JSValueIsUndefined(context, arguments[3]) || !validator.isCallback(arguments[3]))) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTagMifareClassic::incrementBlockValue TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[2])) { + onSuccessForCbm = arguments[2]; + } + if ((argumentCount > 3) && (validator.isCallback(arguments[3]))) { + onErrorForCbm = arguments[3]; + } + + + INFCTagMifareClassicPtr NFCTagMifareClassic(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagMifareClassicIncrementBlockValuePtr event(new EventTagMifareClassicIncrementBlockValue(convert.toInt(arguments[0]), convert.toInt(arguments[1]))); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTagMifareClassic->incrementBlockValue(event); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::incrementBlockValue : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::incrementBlockValue InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCTagMifareClassic::decrementBlockValue(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTagMifareClassicPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 3) { + LogError("JSNFCTagMifareClassic::decrementBlockValue TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if ((JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsNumber(context, arguments[0])) + || (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !JSValueIsNumber(context, arguments[1]))){ + LogError("JSNFCTagMifareClassic::decrementBlockValue TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[2]) || JSValueIsUndefined(context, arguments[2]) || !validator.isCallback(arguments[2])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTagMifareClassic::decrementBlockValue TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 3) && !JSValueIsNull(context, arguments[3]) && (JSValueIsUndefined(context, arguments[3]) || !validator.isCallback(arguments[3]))) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTagMifareClassic::decrementBlockValue TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[2])) { + onSuccessForCbm = arguments[2]; + } + if ((argumentCount > 3) && (validator.isCallback(arguments[3]))) { + onErrorForCbm = arguments[3]; + } + + + INFCTagMifareClassicPtr NFCTagMifareClassic(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagMifareClassicDecrementBlockValuePtr event(new EventTagMifareClassicDecrementBlockValue(convert.toInt(arguments[0]), convert.toInt(arguments[1]))); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTagMifareClassic->decrementBlockValue(event); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::decrementBlockValue : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::decrementBlockValue InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCTagMifareClassic::transfer(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + NFCTagMifareClassicPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 2) { + LogError("JSNFCTagMifareClassic::transfer TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsNumber(context, arguments[0])) { + LogError("JSNFCTagMifareClassic::transfer TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !validator.isCallback(arguments[1])) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTagMifareClassic::transfer TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 2) && !JSValueIsNull(context, arguments[2]) && (JSValueIsUndefined(context, arguments[2]) || !validator.isCallback(arguments[2]))) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTagMifareClassic::transfer TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[1])) { + onSuccessForCbm = arguments[1]; + } + if ((argumentCount > 2) && (validator.isCallback(arguments[2]))) { + onErrorForCbm = arguments[2]; + } + + + INFCTagMifareClassicPtr NFCTagMifareClassic(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagMifareClassicTransferPtr event(new EventTagMifareClassicTransfer(convert.toInt(arguments[0]))); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTagMifareClassic->transfer(event); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::transfer : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::transfer InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCTagMifareClassic::restore(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + NFCTagMifareClassicPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 2) { + LogError("JSNFCTagMifareClassic::restore TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsNumber(context, arguments[0])) { + LogError("JSNFCTagMifareClassic::restore TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !validator.isCallback(arguments[1])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTagMifareClassic::restore TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 2) && !JSValueIsNull(context, arguments[2]) && (JSValueIsUndefined(context, arguments[2]) || !validator.isCallback(arguments[2]))) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTagMifareClassic::restore TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[1])) { + onSuccessForCbm = arguments[1]; + } + if ((argumentCount > 2) && (validator.isCallback(arguments[2]))) { + onErrorForCbm = arguments[2]; + } + + + INFCTagMifareClassicPtr NFCTagMifareClassic(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagMifareClassicRestorePtr event(new EventTagMifareClassicRestore(convert.toInt(arguments[0]))); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTagMifareClassic->restore(event); + + return JSValueMakeNull(context);; + } Catch (ConversionException) { + LogError("JSNFCManager::restore : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::restore InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +} +} diff --git a/src/standards/Tizen/NFC/JSNFCTagMifareClassic.h b/src/standards/Tizen/NFC/JSNFCTagMifareClassic.h new file mode 100755 index 0000000..14b9516 --- /dev/null +++ b/src/standards/Tizen/NFC/JSNFCTagMifareClassic.h @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _JS_TIZEN_NFCTAGMIFARECLASSIC_H_ +#define _JS_TIZEN_NFCTAGMIFARECLASSIC_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject NFCTagMifareClassicPrivObject; + +class JSNFCTagMifareClassic +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, void *tagHandle, void* privManager); + +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSValueRef authenticateWithKeyA(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef authenticateWithKeyB(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef readBlock(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef writeBlock(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef incrementBlockValue(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef decrementBlockValue(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + static JSValueRef transfer(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef restore(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + +}; + +} +} + +#endif /* _JS_TIZEN_NFCTAGMIFARECLASSIC_H_ */ diff --git a/src/standards/Tizen/NFC/JSNFCTagMifareUltra.cpp b/src/standards/Tizen/NFC/JSNFCTagMifareUltra.cpp new file mode 100755 index 0000000..593efc8 --- /dev/null +++ b/src/standards/Tizen/NFC/JSNFCTagMifareUltra.cpp @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "JSNFCTagMifareUltra.h" +#include "NFCConverter.h" +#include "ResponseDispatcher.h" +#include "JSNFCTag.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "plugin_config.h" + + +using namespace TizenApis::Api::NFC; +using namespace TizenApis::Commons; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DPL; + +#define TIZEN10_NFCTTAGMIFAREULTRA_ATTRIBUTENAME "NFCTagMifareUltra" + +namespace TizenApis { +namespace Tizen1_0 { + + JSClassDefinition JSNFCTagMifareUltra::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN10_NFCTTAGMIFAREULTRA_ATTRIBUTENAME, + JSNFCTag::getClassRef(), + NULL, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + + +JSStaticFunction JSNFCTagMifareUltra::m_function[] = { + {"readPage", JSNFCTagMifareUltra::readPage, kJSPropertyAttributeNone}, + {"writePage", JSNFCTagMifareUltra::writePage, kJSPropertyAttributeNone}, + { 0, 0, 0} +}; + +JSClassRef JSNFCTagMifareUltra::m_jsClassRef = JSClassCreate(JSNFCTagMifareUltra::getClassInfo()); + +JSObjectRef JSNFCTagMifareUltra::createJSObject(JSContextRef context, void *tagHandle, void* privManager) { + LogDebug("entered"); + + INFCTagMifareUltraPtr NFCTagMifareUltra = NFCFactory::getInstance().createNFCTagMifareUltraObject(tagHandle); + NFCTagMifareUltra->setPrivateNFCManagerPtr(privManager); + + NFCTagMifareUltraPrivObject *priv = new NFCTagMifareUltraPrivObject(context, NFCTagMifareUltra); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NFCTagMifareUltra object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + +void JSNFCTagMifareUltra::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSNFCTagMifareUltra::finalize(JSObjectRef object) +{ + LogDebug( "entered" ); + NFCTagMifareUltraPrivObject *priv = static_cast( JSObjectGetPrivate( object ) ) ; + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting timezone object"); + delete priv; +} + + +const JSClassRef JSNFCTagMifareUltra::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNFCTagMifareUltra::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSNFCTagMifareUltra::readPage(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTagMifareUltraPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 2) { + LogError("JSNFCTagMifareUltra::readPage TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsNumber(context, arguments[0])) { + LogError("JSNFCTagMifareUltra::readPage TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !validator.isCallback(arguments[1])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTagMifareUltra::readPage TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 2) && !JSValueIsNull(context, arguments[2]) && (JSValueIsUndefined(context, arguments[2]) || !validator.isCallback(arguments[2]))) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTagMifareUltra::readPage TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[1])) { + onSuccessForCbm = arguments[1]; + } + if ((argumentCount > 2) && (validator.isCallback(arguments[2]))) { + onErrorForCbm = arguments[2]; + } + + + INFCTagMifareUltraPtr NFCTagMifareUltra(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagMifareUltraReadPagePtr event(new EventTagMifareUltraReadPage(convert.toInt(arguments[0]))); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTagMifareUltra->readPage(event); + + return JSValueMakeNull(context);; + } Catch (ConversionException) { + LogError("JSNFCManager::readPage : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::readPage InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCTagMifareUltra::writePage(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTagMifareUltraPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 3) { + LogError("JSNFCTagMifareUltra::writePage TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if ((JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsNumber(context, arguments[0])) + || (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !JSIsArrayValue(context, arguments[1]))){ + LogError("JSNFCTagMifareUltra::writePage TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (JSValueIsNull(context, arguments[2]) || JSValueIsUndefined(context, arguments[2]) || !validator.isCallback(arguments[2])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTagMifareUltra::writePage TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 3) && !JSValueIsNull(context, arguments[3]) && (JSValueIsUndefined(context, arguments[3]) || !validator.isCallback(arguments[3]))) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTagMifareUltra::writePage TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[2])) { + onSuccessForCbm = arguments[2]; + } + if ((argumentCount > 3) && (validator.isCallback(arguments[3]))) { + onErrorForCbm = arguments[3]; + } + + + INFCTagMifareUltraPtr NFCTagMifareUltra(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTagMifareUltraWritePagePtr event(new EventTagMifareUltraWritePage(convert.toInt(arguments[0]), convert.toVectorOfUChars(arguments[1]))); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTagMifareUltra->writePage(event); + + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::writePage : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::writePage InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +} +} diff --git a/src/standards/Tizen/NFC/JSNFCTagMifareUltra.h b/src/standards/Tizen/NFC/JSNFCTagMifareUltra.h new file mode 100755 index 0000000..bb33c41 --- /dev/null +++ b/src/standards/Tizen/NFC/JSNFCTagMifareUltra.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _JS_TIZEN_NFCTAGMIFAREULTRA_H_ +#define _JS_TIZEN_NFCTAGMIFAREULTRA_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject NFCTagMifareUltraPrivObject; + +class JSNFCTagMifareUltra +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, void *tagHandle, void* privManager); + +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Getters and setters for properties + */ + + static JSValueRef readPage(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef writePage(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + +}; + +} +} + +#endif /* _JS_TIZEN_NFCTAGMIFAREULTRA_H_ */ diff --git a/src/standards/Tizen/NFC/JSNFCTarget.cpp b/src/standards/Tizen/NFC/JSNFCTarget.cpp new file mode 100755 index 0000000..77b1275 --- /dev/null +++ b/src/standards/Tizen/NFC/JSNFCTarget.cpp @@ -0,0 +1,344 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "JSNFCTarget.h" +#include "JSNFCManager.h" +#include "NFCConverter.h" +#include "ResponseDispatcher.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "plugin_config.h" + + +using namespace TizenApis::Api::NFC; +using namespace TizenApis::Commons; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DPL; + +#define TIZEN10_NFCTARGET_ATTRIBUTENAME "NFCTarget" + +#define TIZEN10_NFCTARGET_ISCONNECTED "isConnected" + +namespace TizenApis { +namespace Tizen1_0 { + + JSClassDefinition JSNFCTarget::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN10_NFCTARGET_ATTRIBUTENAME, + 0, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSNFCTarget::m_property[] = +{ + //NFCTargetProperties + { TIZEN10_NFCTARGET_ISCONNECTED, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSNFCTarget::m_function[] = { + {"setReceiveNDEFListener", JSNFCTarget::setReceiveNDEFListener, kJSPropertyAttributeNone}, + {"unsetReceiveNDEFListener", JSNFCTarget::unsetReceiveNDEFListener, kJSPropertyAttributeNone}, + {"sendNDEF", JSNFCTarget::sendNDEF, kJSPropertyAttributeNone}, + { 0, 0, 0} +}; + +JSClassRef JSNFCTarget::m_jsClassRef = JSClassCreate(JSNFCTarget::getClassInfo()); + +JSObjectRef JSNFCTarget::createJSObject(JSContextRef context, void *tagHandle, void* privManager) { + LogDebug("entered"); + + INFCTargetPtr NFCTarget = NFCFactory::getInstance().createNFCTargetObject(tagHandle); + NFCTarget->setPrivateNFCManagerPtr(privManager); + + NFCTargetPrivObject *priv = new NFCTargetPrivObject(context, NFCTarget); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NFCTarget object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + +void JSNFCTarget::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSNFCTarget::finalize(JSObjectRef object) +{ + LogDebug( "entered" ); + NFCTargetPrivObject *priv = static_cast( JSObjectGetPrivate( object ) ) ; + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting timezone object"); + delete priv; +} + + +const JSClassRef JSNFCTarget::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNFCTarget::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSNFCTarget::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("Enter"); + + Try { + NFCTargetPrivObject* privateObject = static_cast(JSObjectGetPrivate(object)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + INFCTargetPtr NFCTarget(privateObject->getObject()); + NFCConverter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NFCTARGET_ISCONNECTED)) { + NFCManagerPrivObject* privateNFCManager = static_cast(NFCTarget->getPrivateNFCManagerPtr()); + if (!privateNFCManager) { + LogError("NFC Manager Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + INFCManagerPtr NFCManager(privateNFCManager->getObject()); + return convert.toJSValueRef(NFCManager->isValidHandle(NFCTarget->getHandle())); + } + } Catch (ConversionException) { + LogError("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCTarget::setReceiveNDEFListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTargetPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 1) { + LogError("JSNFCTarget::setReceiveNDEFListener TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !validator.isCallback(arguments[0])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTarget::setReceiveNDEFListener TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 1) && !JSValueIsNull(context, arguments[1])){ + if (JSValueIsUndefined(context, arguments[1]) || !validator.isCallback(arguments[1])) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTarget::setReceiveNDEFListener TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[0])) { + onSuccessForCbm = arguments[0]; + } + if (argumentCount > 1) { + if (validator.isCallback(arguments[1])) { + onErrorForCbm = arguments[1]; + } + } + + INFCTargetPtr NFCTarget(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + + EventTargetActionReceiveEmitterPtr emitter(new EventTargetActionReceiveEmitter); + emitter->setListener(&NFCResponseDispatcher::getInstance()); + emitter->setEventPrivateData(StaticPointerCast(callbackManager)); + NFCTarget->setReceiveNDEFListener(emitter); + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::setReceiveNDEFListener : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::setReceiveNDEFListener InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCTarget::unsetReceiveNDEFListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + Try { + NFCTargetPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + INFCTargetPtr NFCTarget(privateObject->getObject()); + NFCTarget->unsetReceiveNDEFListener(); + + return JSValueMakeNull(context); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNFCTarget::sendNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + + NFCTargetPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + NFCConverter convert(context); + Validator validator(context, exception); + + if (argumentCount < 2 ) { + LogError("JSNFCTarget::sendNDEF TypeMismatchException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || !validator.isCallback(arguments[1])) { + /* 1st argument is mandatory. And 1st argument must be Callback. */ + LogError("JSNFCTarget::sendNDEF TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + if ((argumentCount > 2 ) && !JSValueIsNull(context, arguments[2]) && (JSValueIsUndefined(context, arguments[2]) || !validator.isCallback(arguments[2]))) { + /* 2nd argument must be Callback. */ + LogError("JSNFCTarget::sendNDEF TypeMismatchException!"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + void *messageHandle = convert.getMessageHandle(arguments[0]); + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (validator.isCallback(arguments[1])) { + onSuccessForCbm = arguments[1]; + } + + if ((argumentCount > 2 ) && (validator.isCallback(arguments[2]))) { + onErrorForCbm = arguments[2]; + } + + INFCTargetPtr NFCTarget(privateObject->getObject()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(privateObject->getContext(), onSuccessForCbm, onErrorForCbm, true, true); + Try { + callbackManager->setObject( thisObject ); + EventTargetActionSendPtr event(new EventTargetActionSend(messageHandle)); + event->setPrivateData( StaticPointerCast(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + NFCTarget->sendNDEF(event); + return JSValueMakeNull(context); + } Catch (ConversionException) { + LogError("JSNFCManager::sendNDEF : ConversionException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (InvalidArgumentException) { + LogError("JSNFCManager::sendNDEF InvalidArgumentException"); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"Invalid Parameter")); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } + + return JSValueMakeNull(context); +} + +} +} diff --git a/src/standards/Tizen/NFC/JSNFCTarget.h b/src/standards/Tizen/NFC/JSNFCTarget.h new file mode 100755 index 0000000..7c101c0 --- /dev/null +++ b/src/standards/Tizen/NFC/JSNFCTarget.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _JS_TIZEN_NFCTARGET_H_ +#define _JS_TIZEN_NFCTARGET_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject NFCTargetPrivObject; + +class JSNFCTarget +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, void *tagHandle, void* privManager); + +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Getters and setters for properties + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + static JSValueRef setReceiveNDEFListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unsetReceiveNDEFListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef sendNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +} +} + +#endif /* _JS_TIZEN_NFCTARGET_H_ */ diff --git a/src/standards/Tizen/NFC/JSNdefMessage.cpp b/src/standards/Tizen/NFC/JSNdefMessage.cpp new file mode 100755 index 0000000..5635d28 --- /dev/null +++ b/src/standards/Tizen/NFC/JSNdefMessage.cpp @@ -0,0 +1,438 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "JSNdefMessage.h" +#include "JSNdefRecord.h" +#include "NFCConverter.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include "plugin_config.h" + +using namespace TizenApis::Api::NFC; +using namespace TizenApis::Commons; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace { + const char* TIZEN10_NDEFMESSAGE_ATTRIBUTENAME = "NDEFMessage"; + + const char* TIZEN10_NDEFMESSAGE_RECORDCOUNT= "recordCount"; +} + +namespace TizenApis { +namespace Tizen1_0 { + + JSClassDefinition JSNdefMessage::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN10_NDEFMESSAGE_ATTRIBUTENAME, + 0, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSNdefMessage::m_property[] = +{ + //NdefMessageProperties + { TIZEN10_NDEFMESSAGE_RECORDCOUNT, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSNdefMessage::m_function[] = { + {"toByte", JSNdefMessage::toByte, kJSPropertyAttributeNone}, + {"getNDEFRecord", JSNdefMessage::getNDEFRecord, kJSPropertyAttributeNone}, + {"insertNDEFRecord", JSNdefMessage::insertNDEFRecord, kJSPropertyAttributeNone}, + {"appendNDEFRecord", JSNdefMessage::appendNDEFRecord, kJSPropertyAttributeNone}, + {"removeNDEFRecord", JSNdefMessage::removeNDEFRecord, kJSPropertyAttributeNone}, + { 0, 0, 0} +}; + +JSClassRef JSNdefMessage::m_jsClassRef = JSClassCreate(JSNdefMessage::getClassInfo()); + +JSObjectRef JSNdefMessage::createJSObject(JSContextRef context, void *messageHandle) { + LogDebug("entered"); + + INdefMessagePtr NdefMessage = NFCFactory::getInstance().createNDEFMessageObject(messageHandle); + + NdefMessagePrivObject *priv = new NdefMessagePrivObject(context, NdefMessage); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NdefMessage object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + +JSObjectRef JSNdefMessage::createJSObject(JSContextRef context) { + LogDebug("entered"); + + INdefMessagePtr NdefMessage = NFCFactory::getInstance().createNDEFMessageObject(); + + NdefMessagePrivObject *priv = new NdefMessagePrivObject(context, NdefMessage); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NdefMessage object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + +JSObjectRef JSNdefMessage::createJSObject(JSContextRef context, std::vector ndefRcords) { + LogDebug("entered"); + + INdefMessagePtr NdefMessage = NFCFactory::getInstance().createNDEFMessageObject(ndefRcords); + + NdefMessagePrivObject *priv = new NdefMessagePrivObject(context, NdefMessage); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NdefMessage object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + +JSObjectRef JSNdefMessage::createJSObject(JSContextRef context, std::vector rawdata) { + LogDebug("entered"); + + INdefMessagePtr NdefMessage = NFCFactory::getInstance().createNDEFMessageObject(rawdata); + + NdefMessagePrivObject *priv = new NdefMessagePrivObject(context, NdefMessage); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NdefMessage object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} +void JSNdefMessage::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSNdefMessage::finalize(JSObjectRef object) +{ + LogDebug( "entered" ); + NdefMessagePrivObject *priv = static_cast( JSObjectGetPrivate( object ) ) ; + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting NdefMessage object"); + delete priv; +} + + +const JSClassRef JSNdefMessage::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNdefMessage::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSNdefMessage::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("Enter"); + + Try { + NdefMessagePrivObject* privateObject = static_cast(JSObjectGetPrivate(object)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + INdefMessagePtr NdefMessage(privateObject->getObject()); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NDEFMESSAGE_RECORDCOUNT)) { + return convert.toJSValueRefLong(NdefMessage->getRecordCount()); + } + + } Catch (ConversionException) { + LogError("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSNdefMessage::toByte(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + Try { + NdefMessagePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + INdefMessagePtr NdefMessage(privateObject->getObject()); + NFCConverter convert(context); + + return convert.toJSValueRef(NdefMessage->toByte()); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNdefMessage::getNDEFRecord(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + Try { + NdefMessagePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount < 1) { + LogError("Wrong argument count"); + Throw(InvalidArgumentException); + } + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsNumber(context, arguments[0])) { + LogError("Index parameter is JSNull/JSUndefined/Not Number"); + Throw(InvalidArgumentException); + } + + INdefMessagePtr NdefMessage(privateObject->getObject()); + NFCConverter convert(context); + + return JSNdefRecord::createJSObject(privateObject->getContext(), NdefMessage->getNDEFRecord(convert.toLong(arguments[0]))); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNdefMessage::insertNDEFRecord(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + Try { + NdefMessagePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount < 2) { + LogError("Wrong argument count"); + Throw(InvalidArgumentException); + } + if ((JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsNumber(context, arguments[0])) || + (JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1]) || (!JSValueIsObjectOfClass(context, arguments[1], JSNdefRecord::getClassRef())))) { + LogError("Index parameter is JSNull/JSUndefined/Not Number"); + Throw(InvalidArgumentException); + } + + INdefMessagePtr NdefMessage(privateObject->getObject()); + NFCConverter convert(context); + + long index = convert.toLong(arguments[0]); + void *record = convert.getRecordHandle(arguments[1]); + + NdefMessage->insertNDEFRecord(index, record); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSNdefMessage::appendNDEFRecord(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + Try { + NdefMessagePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount < 1) { + LogError("Wrong argument count"); + Throw(InvalidArgumentException); + } + + INdefMessagePtr NdefMessage(privateObject->getObject()); + NFCConverter convert(context); + + void *record = convert.getRecordHandle(arguments[0]); + + NdefMessage->appendNDEFRecord(record); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSNdefMessage::removeNDEFRecord(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + Try { + NdefMessagePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argumentCount < 1) { + LogError("Wrong argument count"); + Throw(InvalidArgumentException); + } + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) || !JSValueIsNumber(context, arguments[0])) { + LogError("Index parameter is JSNull/JSUndefined/Not Number"); + Throw(InvalidArgumentException); + } + + INdefMessagePtr NdefMessage(privateObject->getObject()); + NFCConverter convert(context); + + NdefMessage->removeNDEFRecord(convert.toLong(arguments[0])); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +} +} diff --git a/src/standards/Tizen/NFC/JSNdefMessage.h b/src/standards/Tizen/NFC/JSNdefMessage.h new file mode 100755 index 0000000..983f72c --- /dev/null +++ b/src/standards/Tizen/NFC/JSNdefMessage.h @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _JS_TIZEN_NDEFMESSAGE_H_ +#define _JS_TIZEN_NDEFMESSAGE_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject NdefMessagePrivObject; + +class JSNdefMessage +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context); + static JSObjectRef createJSObject(JSContextRef context, void *messageHandle); + static JSObjectRef createJSObject(JSContextRef context, std::vector ndefRcords); + static JSObjectRef createJSObject(JSContextRef context, std::vector rawdata); + +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Getters and setters for properties + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + static JSValueRef toByte(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getNDEFRecord(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef insertNDEFRecord(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef appendNDEFRecord(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef removeNDEFRecord(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +} +} + +#endif /* _JS_TIZEN_NDEFMESSAGE_H_ */ diff --git a/src/standards/Tizen/NFC/JSNdefRecord.cpp b/src/standards/Tizen/NFC/JSNdefRecord.cpp new file mode 100755 index 0000000..744fc2e --- /dev/null +++ b/src/standards/Tizen/NFC/JSNdefRecord.cpp @@ -0,0 +1,300 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include "JSNdefRecord.h" +#include "plugin_config.h" +#include "NFCConverter.h" + +namespace TizenApis { +namespace Tizen1_0 { + +using namespace TizenApis::Commons; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace Api::NFC; + +#define TIZEN10_NDEFRECORD_PROPERTIES "properties" + +#define TIZEN10_NDEFRECORD_TEXT_TEXT "text" +#define TIZEN10_NDEFRECORD_TEXT_LANGCODE "langCode" +#define TIZEN10_NDEFRECORD_TEXT_ENCODETYPE "encodeType" + +#define TIZEN10_NDEFRECORD_URI_URI "uri" + +#define TIZEN10_NDEFRECORD_MEDIA_MIMETYPE "mimeType" + +JSClassDefinition JSNdefRecord::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "NDEFRecord", + 0, + m_property, + m_function, + initialize, + finalize, + NULL, //HasProperty, + NULL, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + +JSStaticValue JSNdefRecord::m_property[] = +{ + {TIZEN10_NDEFRECORD_PROPERTIES, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN10_NDEFRECORD_TEXT_TEXT, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN10_NDEFRECORD_TEXT_LANGCODE, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN10_NDEFRECORD_TEXT_ENCODETYPE, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN10_NDEFRECORD_URI_URI, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN10_NDEFRECORD_MEDIA_MIMETYPE, getProperty, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSNdefRecord::m_function[] = { + {"getPayload", JSNdefRecord::getPayload, kJSPropertyAttributeNone}, + { 0, 0, 0} +}; + +const JSClassRef JSNdefRecord::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNdefRecord::getClassInfo() { + return &m_classInfo; +} + +JSClassRef JSNdefRecord::m_jsClassRef = JSClassCreate(JSNdefRecord::getClassInfo()); + +JSObjectRef JSNdefRecord::createJSObject(JSContextRef context, const NdefRecordData &ndefRecordData) { + LogDebug("Entered"); + return createJSObject(context, ndefRecordData.properties, ndefRecordData.payload); +} + +JSObjectRef JSNdefRecord::createJSObject(JSContextRef context, const NdefRecordProperties &ndefRecordProperties, std::vector payload) { + INdefRecordPtr NdefRecord = NFCFactory::getInstance().createNDEFRecordObject(ndefRecordProperties, payload); + + NdefRecordPrivObject *priv = new NdefRecordPrivObject(context, NdefRecord); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NdefRecord object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + +JSObjectRef JSNdefRecord::createJSObject(JSContextRef context, const std::string &text, const std::string &langCode, const short encodeType) { + INdefRecordPtr NdefRecord = NFCFactory::getInstance().createNDEFRecordObject(text, langCode, encodeType); + + NdefRecordPrivObject *priv = new NdefRecordPrivObject(context, NdefRecord); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NdefRecord object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + +JSObjectRef JSNdefRecord::createJSObject(JSContextRef context, const std::string &uri) { + INdefRecordPtr NdefRecord = NFCFactory::getInstance().createNDEFRecordObject(uri); + + NdefRecordPrivObject *priv = new NdefRecordPrivObject(context, NdefRecord); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NdefRecord object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + +JSObjectRef JSNdefRecord::createJSObject(JSContextRef context, const std::string &mimeType, std::vector data) { + INdefRecordPtr NdefRecord = NFCFactory::getInstance().createNDEFRecordObject(mimeType, data); + + NdefRecordPrivObject *priv = new NdefRecordPrivObject(context, NdefRecord); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NdefRecord object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + +void JSNdefRecord::initialize(JSContextRef context, JSObjectRef object) { + LogDebug("Entered. Nothing to do."); +} + +void JSNdefRecord::finalize(JSObjectRef object) { + LogDebug("Entered"); + NdefRecordPrivObject* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting ndefrecord object"); + delete priv; +} + +JSValueRef JSNdefRecord::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) { + LogDebug("Enter"); + + Try { + NFCConverter convert(context); + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NDEFRECORD_PROPERTIES)) { + NdefRecordPrivObject *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object not set."); + } + INdefRecordPtr NdefRecord = priv->getObject(); + NdefRecordProperties props = NdefRecord->getNDEFRecordProperties(); + + return convert.toJSValueRef(props); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NDEFRECORD_TEXT_TEXT)) { + NdefRecordPrivObject *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object not set."); + } + INdefRecordPtr NdefRecord = priv->getObject(); + char * text = NULL; + if (NdefRecord->getText(&text)) { + std::string result(text); + free(text); + LogDebug("text : " << result); + return convert.toJSValueRef(result); + } + LogDebug("This record is not Text Type"); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NDEFRECORD_TEXT_LANGCODE)) { + NdefRecordPrivObject *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object not set."); + } + INdefRecordPtr NdefRecord = priv->getObject(); + char * landCode = NULL; + if (NdefRecord->getLangCode(&landCode)) { + std::string result(landCode); + free(landCode); + LogDebug("landCode : " << result); + return convert.toJSValueRef(result); + } + LogDebug("This record is not Text Type"); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NDEFRECORD_TEXT_ENCODETYPE)) { + NdefRecordPrivObject *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object not set."); + } + INdefRecordPtr NdefRecord = priv->getObject(); + nfcTextEncodeUTF encodeType = NFC_TEXT_ENCODE_UTF_16; + if (NdefRecord->getEncodeType(&encodeType)) { + LogDebug("encodeType : " << encodeType); + return convert.toJSValueRef(convert.toNfcTextEncodeUTFString(encodeType)); + } + LogDebug("This record is not Text Type"); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NDEFRECORD_URI_URI)) { + NdefRecordPrivObject *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object not set."); + } + INdefRecordPtr NdefRecord = priv->getObject(); + char * uri = NULL; + if (NdefRecord->getUri(&uri)) { + std::string result(uri); + free(uri); + LogDebug("uri : " << result); + return convert.toJSValueRef(result); + } + LogDebug("This record is not URI Type"); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN10_NDEFRECORD_MEDIA_MIMETYPE)) { + NdefRecordPrivObject *priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object not set."); + } + INdefRecordPtr NdefRecord = priv->getObject(); + char * mimeType = NULL; + if (NdefRecord->getMimeType(&mimeType)) { + std::string result(mimeType); + free(mimeType); + LogDebug("mimeType : " << result); + return convert.toJSValueRef(result); + } + LogDebug("This record is not MEDIA Type"); + } + + } Catch (ConversionException) { + LogError("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (NullPointerException) { + LogError("NullPointerException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSNdefRecord::getPayload(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + Try { + NdefRecordPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = NFC_CHECK_ACCESS(privateObject->getContext(),NFC_FUNCTION_API_TAG_P2P_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + INdefRecordPtr NdefRecord(privateObject->getObject()); + NFCConverter convert(context); + + return convert.toJSValueRef(NdefRecord->getPayload()); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +} //Tizen1_0 +} //TizenApis + diff --git a/src/standards/Tizen/NFC/JSNdefRecord.h b/src/standards/Tizen/NFC/JSNdefRecord.h new file mode 100755 index 0000000..03d8ef5 --- /dev/null +++ b/src/standards/Tizen/NFC/JSNdefRecord.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef WRTPLUGINS_TIZEN_JS_NDEFRECORD_H_ +#define WRTPLUGINS_TIZEN_JS_NDEFRECORD_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject NdefRecordPrivObject; + +class JSNdefRecord +{ +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, + const Api::NFC::NdefRecordData &ndefRecordData); + static JSObjectRef createJSObject(JSContextRef context, + const Api::NFC::NdefRecordProperties &ndefRecordProperties, std::vector payload); + + static JSObjectRef createJSObject(JSContextRef context, const std::string &text, + const std::string &langCode, const short encodeType); + static JSObjectRef createJSObject(JSContextRef context, const std::string &uri); + static JSObjectRef createJSObject(JSContextRef context, + const std::string &mimeType, std::vector data); +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + static JSValueRef getPayload(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +} //Tizen1_0 +} //TizenApis + +#endif + diff --git a/src/standards/Tizen/NFC/NFCChangedCallback.h b/src/standards/Tizen/NFC/NFCChangedCallback.h new file mode 100755 index 0000000..da73f2e --- /dev/null +++ b/src/standards/Tizen/NFC/NFCChangedCallback.h @@ -0,0 +1,38 @@ +/* +* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef TIZEN_NFC_NFCCHANGEDCALLBACK_H_ +#define TIZEN_NFC_NFCCHANGEDCALLBACK_H_ + +#include + +namespace TizenApis { +namespace Tizen1_0 { +struct NFCChangedCallback +{ + JSValueRef onAttach; + JSValueRef onDetach; + + NFCChangedCallback() : + onAttach(NULL), + onDetach(NULL) + { + } +}; +} +} + +#endif diff --git a/src/standards/Tizen/NFC/NFCConverter.cpp b/src/standards/Tizen/NFC/NFCConverter.cpp new file mode 100755 index 0000000..fb73b04 --- /dev/null +++ b/src/standards/Tizen/NFC/NFCConverter.cpp @@ -0,0 +1,366 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#include +#include +#include +#include +#include "NFCConverter.h" +#include "JSNdefRecord.h" +#include "JSNdefMessage.h" + +using namespace std; +using namespace TizenApis::Api::NFC; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis; + + +#define NFC_FILTER_ATTRIBUTE_TAG_TYPES "tagTypes" + +#define NFC_CHANGED_CALLBACK_ONATTATCH "onAttach" +#define NFC_CHANGED_CALLBACK_ONDETACH "onDetach" + +namespace TizenApis { +namespace Tizen1_0 { + +vector NFCConverter::m_allowedTagFilterProperties; + +NFCConverter::NFCConverter(JSContextRef context) : Converter(context) +{ + LogDebug("entered"); + static bool init = initializeAllowedProperties(); + (void) init; +} + +NFCConverter::~NFCConverter() +{ + LogDebug("entered"); +} + +TagFilterPtr NFCConverter::toNFCTagFilter(JSValueRef jsValue) +{ + LogDebug("entered"); + if (JSValueIsNull(m_context, jsValue) || + JSValueIsUndefined(m_context, jsValue)) { + return TagFilterPtr(); //empty filter + } + TagFilterPtr filter(new TagFilter()); + + Validator validator(m_context); + + if (!JSValueIsUndefined(m_context, jsValue)) { + vector filter_values(toVectorOfStrings(jsValue)); + + LogDebug("NFCConverter, start setting filter values, tag_types.size() : " << filter_values.size()); + for (unsigned int i=0; iaddTagTypeValue(filterValue); + LogDebug("NFCConverter, tag_types.at(i): " << filter_values.at(i)); + } + } + LogDebug("NFCConverter, filter size == " << filter->getFilterSize()); + + return filter; +} + + +nfcTagType NFCConverter::toNfcTagType(std::string typeString) { + if (typeString == "ISO14443_A") + return NFC_TAGTYPE_ISO14443_A_PICC; + else if (typeString == "ISO14443_4A") + return NFC_TAGTYPE_ISO14443_4A_PICC; + else if (typeString == "ISO14443_3A") + return NFC_TAGTYPE_ISO14443_3A_PICC; + else if (typeString == "MIFARE_MINI") + return NFC_TAGTYPE_MIFARE_MINI_PICC; + else if (typeString == "MIFARE_1K") + return NFC_TAGTYPE_MIFARE_1K_PICC; + else if (typeString == "MIFARE_4K") + return NFC_TAGTYPE_MIFARE_4K_PICC; + else if (typeString == "MIFARE_ULTRA") + return NFC_TAGTYPE_MIFARE_ULTRA_PICC; + else if (typeString == "MIFARE_DESFIRE") + return NFC_TAGTYPE_MIFARE_DESFIRE_PICC; + else if (typeString == "ISO14443_B") + return NFC_TAGTYPE_ISO14443_B_PICC; + else if (typeString == "ISO14443_4B") + return NFC_TAGTYPE_ISO14443_4B_PICC; + else if (typeString == "ISO14443_BPRIME") + return NFC_TAGTYPE_ISO14443_BPRIME_PICC; + else if (typeString == "FELICA") + return NFC_TAGTYPE_FELICA_PICC; + else if (typeString == "JEWEL") + return NFC_TAGTYPE_JEWEL_PICC; + else if (typeString == "ISO15693") + return NFC_TAGTYPE_ISO15693_PICC; + else + ThrowMsg(Commons::InvalidArgumentException, "No Match Tag Type"); +} + +std::string NFCConverter::toNfcTagTypeString(nfcTagType type) { + switch (type) { + case NFC_TAGTYPE_GENERIC_PICC: + return "GENERIC_TARGET"; + break; + case NFC_TAGTYPE_ISO14443_A_PICC: + return "ISO14443_A"; + break; + case NFC_TAGTYPE_ISO14443_4A_PICC: + return "ISO14443_4A"; + break; + case NFC_TAGTYPE_ISO14443_3A_PICC: + return "ISO14443_3A"; + break; + case NFC_TAGTYPE_MIFARE_MINI_PICC: + return "MIFARE_MINI"; + break; + case NFC_TAGTYPE_MIFARE_1K_PICC: + return "MIFARE_1K"; + break; + case NFC_TAGTYPE_MIFARE_4K_PICC: + return "MIFARE_4K"; + break; + case NFC_TAGTYPE_MIFARE_ULTRA_PICC: + return "MIFARE_ULTRA"; + break; + case NFC_TAGTYPE_MIFARE_DESFIRE_PICC: + return "MIFARE_DESFIRE"; + break; + case NFC_TAGTYPE_ISO14443_B_PICC: + return "ISO14443_B"; + break; + case NFC_TAGTYPE_ISO14443_4B_PICC: + return "ISO14443_4B"; + break; + case NFC_TAGTYPE_ISO14443_BPRIME_PICC: + return "ISO14443_BPRIME"; + break; + case NFC_TAGTYPE_FELICA_PICC: + return "FELICA"; + break; + case NFC_TAGTYPE_JEWEL_PICC: + return "JEWEL"; + break; + case NFC_TAGTYPE_ISO15693_PICC: + return "ISO15693"; + break; + case NFC_TAGTYPE_UNKNOWN_TARGET: + default: + return "UNKNOWN_TARGET"; + break; + } +} + +nfcTextEncodeUTF NFCConverter::toNfcTextEncodeUTF(std::string encodeString) { + if (encodeString == "UTF-8") + return NFC_TEXT_ENCODE_UTF_8; + else if (encodeString == "UTF-16") + return NFC_TEXT_ENCODE_UTF_16; + else + Throw(ConversionException); +} + +std::string NFCConverter::toNfcTextEncodeUTFString(nfcTextEncodeUTF encode) { + switch(encode) { + case NFC_TEXT_ENCODE_UTF_8: + return "UTF-8"; + break; + case NFC_TEXT_ENCODE_UTF_16: + return "UTF-16"; + break; + default: + Throw(ConversionException); + } +} +bool NFCConverter::initializeAllowedProperties() +{ + LogDebug("entered"); + //NFC Filter properties + m_allowedTagFilterProperties.push_back(NFC_FILTER_ATTRIBUTE_TAG_TYPES); + return true; +} + +JSValueRef NFCConverter::toJSValueRef(const std::vector& arg) { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(Commons::NullPointerException, "Could not create js array object"); + } + + for (std::size_t i = 0; i < arg.size(); ++i) { + JSValueRef tmpVal = JSValueMakeNumber(m_context, arg[i]); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(Commons::UnknownException, "Could not insert value into js array"); + } + } + + return jsResult; +} + +JSValueRef NFCConverter::toJSValueRef(NdefRecordProperties props) { + JSObjectRef propertyRef = JSObjectMake(m_context, NULL, NULL); + + ScopedJSStringRef jsTNFString(JSStringCreateWithUTF8CString("tnf")); + ScopedJSStringRef jsTypeString(JSStringCreateWithUTF8CString("typeName")); + ScopedJSStringRef jsIdString(JSStringCreateWithUTF8CString("id")); + + JSObjectSetProperty(m_context, propertyRef, jsTNFString.get(), toJSValueRef(static_cast(props.tnf)), kJSPropertyAttributeNone, NULL); + JSObjectSetProperty(m_context, propertyRef, jsTypeString.get(), toJSValueRef(props.typeName), kJSPropertyAttributeNone, NULL); + JSObjectSetProperty(m_context, propertyRef, jsIdString.get(), toJSValueRef(props.id), kJSPropertyAttributeNone, NULL); + + return propertyRef; +} + +JSValueRef NFCConverter::toJSValueRef(std::vector props) { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Could not create js array object"); + } + + for (std::size_t i = 0; i < props.size(); ++i) { + JSValueRef tmpVal = toJSValueRef(props[i].value); + if (!JSSetArrayElementInArrayList(m_context, jsResult, props[i].key.c_str(), tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + return jsResult; +} + +NdefRecordProperties NFCConverter::toNdefRecordProperties(JSValueRef value, JSValueRef* exception) { + if (JSValueIsNull(m_context, value) || JSValueIsUndefined(m_context, value)) { + ThrowMsg(Commons::InvalidArgumentException, + "Message is JS null or JS undefined."); + } + JSObjectRef obj = toJSObjectRef(value); + + if (!obj) { + LogError("Object is null"); + ThrowMsg(Commons::NullPointerException, "Private object not initialized"); + } + + NdefRecordProperties props; + JSValueRef tnf_JSProperty = JSUtils::getJSProperty(m_context, value, "tnf", exception); + JSValueRef type_JSProperty = JSUtils::getJSProperty(m_context, value, "typeName", exception); + JSValueRef id_JSProperty = JSUtils::getJSProperty(m_context, value, "id", exception); + + if (tnf_JSProperty != NULL && JSValueIsNumber(m_context, tnf_JSProperty)) { + props.tnf = static_cast(toLong(tnf_JSProperty)); + } + + props.typeName= toVectorOfUChars(type_JSProperty); + props.id= toVectorOfUChars(id_JSProperty); + + return props; +} + +std::vector NFCConverter::toVectorOfRecordHandles(const JSValueRef& arg) { + if (JSValueIsNull(m_context, arg) || JSValueIsUndefined(m_context, arg)) { + ThrowMsg(Commons::InvalidArgumentException, + "NdefRecordArray is JS null or JS undefined."); + } + + if (!JSIsArrayValue(m_context, arg)) { + ThrowMsg(Commons::ConversionException, "Argument is not an JS array."); + } + + std::vector result; + JSObjectRef objArg = toJSObjectRef(arg); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, objArg); ++i) { + JSValueRef element = JSGetArrayElement(m_context, objArg, i); + result.push_back(getRecordHandle(element)); + } + return result; +} + +void *NFCConverter::getRecordHandle(const JSValueRef& arg) { + if (JSValueIsNull(m_context, arg) || JSValueIsUndefined(m_context, arg) || + (!JSValueIsObjectOfClass(m_context, arg, JSNdefRecord::getClassRef()))) { + ThrowMsg(Commons::InvalidArgumentException, + "Message is JS null or JS undefined."); + } + JSObjectRef obj = toJSObjectRef(arg); + + if (!obj) { + LogError("Object is null"); + ThrowMsg(Commons::NullPointerException, "Private object not initialized"); + } + NdefRecordPrivObject* privateObject = static_cast(JSObjectGetPrivate(obj)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(Commons::NullPointerException, "Private object not initialized"); + } + + INdefRecordPtr record = privateObject->getObject(); + + return record->getHandle(); +} + +void *NFCConverter::getMessageHandle(const JSValueRef& arg) { + if (JSValueIsNull(m_context, arg) || JSValueIsUndefined(m_context, arg) || + (!JSValueIsObjectOfClass(m_context, arg, JSNdefMessage::getClassRef()))) { + ThrowMsg(Commons::InvalidArgumentException, + "Message is JS null or JS undefined."); + } + JSObjectRef obj = toJSObjectRef(arg); + + if (!obj) { + LogError("Object is null"); + ThrowMsg(Commons::NullPointerException, "Private object not initialized"); + } + NdefMessagePrivObject* privateObject = static_cast(JSObjectGetPrivate(obj)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(Commons::NullPointerException, "Private object not initialized"); + } + + INdefMessagePtr message = privateObject->getObject(); + + return message->getHandle(); +} + +NFCChangedCallback NFCConverter::toNFCChangedCallback(const JSValueRef& arg) { + LogDebug("Entered"); + JSObjectRef object = toJSObjectRef(arg); + + NFCChangedCallback result; + Validator validator(m_context); + + result.onAttach= JSUtils::getJSPropertyOrUndefined( + m_context, object, NFC_CHANGED_CALLBACK_ONATTATCH + ); + if (!validator.isNullOrUndefined(result.onAttach) && + !validator.isCallback(result.onAttach)) { + ThrowMsg(Commons::ConversionException, "Not a valid callback."); + } + + result.onDetach= JSUtils::getJSPropertyOrUndefined( + m_context, object, NFC_CHANGED_CALLBACK_ONDETACH + ); + if (!validator.isNullOrUndefined(result.onDetach) && + !validator.isCallback(result.onDetach)) { + ThrowMsg(Commons::ConversionException, "Not a valid callback."); + } + + return result; +} + +} +} diff --git a/src/standards/Tizen/NFC/NFCConverter.h b/src/standards/Tizen/NFC/NFCConverter.h new file mode 100755 index 0000000..c59299c --- /dev/null +++ b/src/standards/Tizen/NFC/NFCConverter.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef _JS_TIZEN10_NFC_CONVERTER_H_ +#define _JS_TIZEN10_NFC_CONVERTER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include "NFCChangedCallback.h" + +using namespace TizenApis::Api::NFC; + +namespace TizenApis { +namespace Tizen1_0 { + + +class NFCConverter : public WrtDeviceApis::CommonsJavaScript::Converter +{ + public: + using WrtDeviceApis::CommonsJavaScript::Converter::toJSValueRef; + public: + explicit NFCConverter(JSContextRef context); + virtual ~NFCConverter(); + TagFilterPtr toNFCTagFilter(JSValueRef jsValue); + nfcTagType toNfcTagType(std::string typeString); + std::string toNfcTagTypeString(nfcTagType type); + nfcTextEncodeUTF toNfcTextEncodeUTF(std::string encodeString); + std::string toNfcTextEncodeUTFString(nfcTextEncodeUTF encode); + JSValueRef toJSValueRef(const std::vector& arg); + JSValueRef toJSValueRef(NdefRecordProperties props); + JSValueRef toJSValueRef(std::vector props); + NdefRecordProperties toNdefRecordProperties(JSValueRef value, JSValueRef* exception); + std::vector toVectorOfRecordHandles(const JSValueRef& arg); + void *getRecordHandle(const JSValueRef& arg); + void *getMessageHandle(const JSValueRef& arg); + NFCChangedCallback toNFCChangedCallback(const JSValueRef& arg); + + private: + bool initializeAllowedProperties(); + static std::vector m_allowedTagFilterProperties; +}; + +typedef WrtDeviceApis::CommonsJavaScript::ConverterFactory NFCConverterFactory; + +} +} + +#endif /* _JS_TIZEN10_NFC_CONVERTER_H_ */ diff --git a/src/standards/Tizen/NFC/NFCStaticController.cpp b/src/standards/Tizen/NFC/NFCStaticController.cpp new file mode 100755 index 0000000..08a631c --- /dev/null +++ b/src/standards/Tizen/NFC/NFCStaticController.cpp @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include + +#include +#include +#include +#include +#include + +#include "NFCStaticController.h" +#include "EventNFCChangedPrivateData.h" +#include "JSNFCTag.h" +#include "JSNFCTagMifareClassic.h" +#include "JSNFCTagMifareUltra.h" +#include "JSNFCTarget.h" +#include "JSNdefMessage.h" + +using namespace TizenApis::Api::NFC; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { + +NFCStaticController& NFCStaticController::getInstance() { + static NFCStaticController controller; + return controller; +} + +NFCStaticController::NFCStaticController() : + EventNFCChangedListener(ThreadEnum::NULL_THREAD), + EventNFCChangedNdefListener(ThreadEnum::NULL_THREAD), + EventNFCChangedSeEventListener(ThreadEnum::NULL_THREAD){ +} + +void NFCStaticController::onAnswerReceived(const EventNFCChangedPtr& event) { + LogDebug("onAnswerReceived Enter"); + + EventNFCChangedPrivateDataPtr privateData = + DPL::DynamicPointerCast(event->getPrivateData()); + + void *nfcProp = event->getNFCProperties(); + + Try { + /** + *When received answer from platform, create an NFCTag JSObject and then call success function. + */ + if (nfcProp != NULL) { + JSObjectRef nfcObj; + JSCallbackManagerPtr callbackManager = privateData->getCallbackManager(); + JSContextRef context = callbackManager->getContext(); + + if (event->getNFCType() == NFC_TAG_TYPE) + nfcObj = JSNFCTag::createJSObject(context, nfcProp, event->getPrivateNFCManagerPtr()); + else if (event->getNFCType() == NFC_TAG_MIFARE_CLASSIC_TYPE) + nfcObj = JSNFCTagMifareClassic::createJSObject(context, nfcProp, event->getPrivateNFCManagerPtr()); + else if (event->getNFCType() == NFC_TAG_MIFARE_ULTRA_TYPE) + nfcObj = JSNFCTagMifareUltra::createJSObject(context, nfcProp, event->getPrivateNFCManagerPtr()); + else + nfcObj = JSNFCTarget::createJSObject(context, nfcProp, event->getPrivateNFCManagerPtr()); + LogDebug("callOnSuccess"); + callbackManager->callOnSuccess(static_cast(nfcObj)); + } else { + JSCallbackManagerPtr detachedCallbackManager = privateData->getDetachedCallbackManager(); + + detachedCallbackManager->callOnSuccess(); + } + } Catch (ConversionException) { + LogError("Conversion exception while processing EventNFCChanged"); + } +} + +void NFCStaticController::onAnswerReceived(const EventNFCChangedNdefPtr& event) { + LogDebug("onAnswerReceived Enter"); + + Try { + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + cbm->callOnSuccess(JSNdefMessage::createJSObject(cbm->getContext(), event->getReadNdefResult())); + } Catch (PlatformException) { + LogError("Platform can't create NdefMessage" << _rethrown_exception.GetMessage()); + } Catch (Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } +} + +void NFCStaticController::onAnswerReceived(const EventNFCChangedSeEventPtr& event) { + LogDebug("onAnswerReceived Enter"); + + Try { + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + Converter convert(cbm->getContext()); + std::string seEventString; + switch (event->getSeEvent()) { + case NFC_SE_EVENTTYPE_START_TRANSACTION: + seEventString = "BEGIN_TRANSACTION"; + break; + case NFC_SE_EVENTTYPE_END_TRANSACTION: + seEventString = "END_TRANSACTION"; + break; + case NFC_SE_EVENTTYPE_CONNECTIVITY: + seEventString = "CONNECT"; + break; + case NFC_SE_EVENTTYPE_FIELD_ON: + seEventString = "FIELD_ON"; + break; + case NFC_SE_EVENTTYPE_FIELD_OFF: + seEventString = "FIELD_OFF"; + break; + default: + ThrowMsg(ConversionException, "No Match SE EVENT"); + } + cbm->callOnSuccess(convert.toJSValueRef(seEventString)); + } Catch (ConversionException) { + LogError("Conversion exception while processing EventNFCChangedSeEventPtr" << _rethrown_exception.GetMessage()); + } Catch (Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } +} + +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/NFC/NFCStaticController.h b/src/standards/Tizen/NFC/NFCStaticController.h new file mode 100755 index 0000000..af660a0 --- /dev/null +++ b/src/standards/Tizen/NFC/NFCStaticController.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef WRTPLUGINS_TIZEN_NFC_STATIC_CONTROLLER_H_ +#define WRTPLUGINS_TIZEN_NFC_STATIC_CONTROLLER_H_ + +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +using namespace WrtDeviceApis::Commons; +using namespace Api::NFC; +typedef EventListener< EventNFCChanged > EventNFCChangedListener; +typedef EventListener< EventNFCChangedNdef > EventNFCChangedNdefListener; +typedef EventListener< EventNFCChangedSeEvent > EventNFCChangedSeEventListener; + +class NFCStaticController : + public EventNFCChangedListener, + public EventNFCChangedNdefListener, + public EventNFCChangedSeEventListener +{ +public: + static NFCStaticController& getInstance(); + + void onAnswerReceived(const EventNFCChangedPtr& event); + void onAnswerReceived(const EventNFCChangedNdefPtr& event); + void onAnswerReceived(const EventNFCChangedSeEventPtr& event); + +protected: + NFCStaticController(); +}; + + +} // Tizen1_0 +} // TizenApis + +#endif /* WRTPLUGINS_TIZEN_NFC_STATIC_CONTROLLER_H_ */ + diff --git a/src/standards/Tizen/NFC/ResponseDispatcher.cpp b/src/standards/Tizen/NFC/ResponseDispatcher.cpp new file mode 100755 index 0000000..6d5f76f --- /dev/null +++ b/src/standards/Tizen/NFC/ResponseDispatcher.cpp @@ -0,0 +1,452 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include "ResponseDispatcher.h" +#include "NFCConverter.h" +#include "JSNdefMessage.h" + + +using namespace TizenApis::Api::NFC; +using namespace TizenApis::Commons; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +namespace TizenApis { +namespace Tizen1_0 { + +NFCResponseDispatcher& NFCResponseDispatcher::getInstance() +{ + static NFCResponseDispatcher instance; + return instance; +} + +NFCResponseDispatcher::NFCResponseDispatcher() : + readNDEFAnswerReceiver(ThreadEnum::NULL_THREAD), + writeNDEFAnswerReceiver(ThreadEnum::NULL_THREAD), + transceiveAnswerReceiver(ThreadEnum::NULL_THREAD), + formatAnswerReceiver(ThreadEnum::NULL_THREAD), + mifareClassicAuthenticateWithKeyAAnswerReceiver(ThreadEnum::NULL_THREAD), + mifareClassicAuthenticateWithKeyBAnswerReceiver(ThreadEnum::NULL_THREAD), + mifareClassicReadBlockAnswerReceiver(ThreadEnum::NULL_THREAD), + mifareClassicWriteBlockAnswerReceiver(ThreadEnum::NULL_THREAD), + mifareClassicIncrementBlockValueAnswerReceiver(ThreadEnum::NULL_THREAD), + mifareClassicDecrementBlockValueAnswerReceiver(ThreadEnum::NULL_THREAD), + mifareClassicTransferAnswerReceiver(ThreadEnum::NULL_THREAD), + mifareClassicRestoreAnswerReceiver(ThreadEnum::NULL_THREAD), + mifareUltraReadPageAnswerReceiver(ThreadEnum::NULL_THREAD), + mifareUltraWritePageAnswerReceiver(ThreadEnum::NULL_THREAD), + TargetSendNdefAnswerReceiver(ThreadEnum::NULL_THREAD), + TargetReceiveNdefListener(ThreadEnum::NULL_THREAD) +{ + LogDebug("entered"); +} + +NFCResponseDispatcher::~NFCResponseDispatcher() +{ + LogDebug("entered"); +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagActionReadPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + Try { + if (!cbm) { + LogDebug("no callback manager"); + return; + } + if (event->getResult()) { + LogDebug("result success"); + cbm->callOnSuccess(JSNdefMessage::createJSObject(cbm->getContext(), event->getReadNdefResult())); + return; + } + LogDebug("result fail"); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } Catch (PlatformException) { + LogError("Platform can't create NdefMessage" << _rethrown_exception.GetMessage()); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } Catch (Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagActionWritePtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + JSContextRef context = cbm->getContext(); + + if (event->getResult()) { + LogDebug("result success"); + cbm->callOnSuccess(); + return; + } + LogDebug("result fail"); + + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagActionTransceivePtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + Try { + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + JSContextRef context = cbm->getContext(); + + if (event->getResult()) { + NFCConverter convert(context); + LogDebug("result success"); + cbm->callOnSuccess(convert.toJSValueRef(event->getTransceiveBuffer())); + return; + } + LogDebug("result fail"); + + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } Catch (ConversionException) { + LogError("Conversion exception while processing EventTagActionTransceive"); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } Catch (Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagActionFormatPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + JSContextRef context = cbm->getContext(); + + if (event->getResult()) { + LogDebug("result success"); + cbm->callOnSuccess(); + return; + } + LogDebug("result fail"); + + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); +} + + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagMifareClassicAuthenticateWithKeyAPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + if (!cbm) { + LogDebug("no callback manager"); + return; + } + if (event->getResult()) { + LogDebug("result success"); + cbm->callOnSuccess(); + return; + } + LogDebug("result fail"); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagMifareClassicAuthenticateWithKeyBPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + JSContextRef context = cbm->getContext(); + + if (event->getResult()) { + LogDebug("result success"); + cbm->callOnSuccess(); + return; + } + LogDebug("result fail"); + + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagMifareClassicReadBlockPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + Try { + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + JSContextRef context = cbm->getContext(); + + if (event->getResult()) { + NFCConverter convert(context); + LogDebug("result success"); + cbm->callOnSuccess(convert.toJSValueRef(event->getBlockData())); + return; + } + LogDebug("result fail"); + + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); + } Catch (ConversionException) { + LogError("Conversion exception while processing EventTagMifareClassicReadBlock"); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } Catch (Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagMifareClassicWriteBlockPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + if (!cbm) { + LogDebug("no callback manager"); + return; + } + if (event->getResult()) { + LogDebug("result success"); + cbm->callOnSuccess(); + return; + } + LogDebug("result fail"); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagMifareClassicIncrementBlockValuePtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + JSContextRef context = cbm->getContext(); + + if (event->getResult()) { + LogDebug("result success"); + cbm->callOnSuccess(); + return; + } + LogDebug("result fail"); + + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagMifareClassicDecrementBlockValuePtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + JSContextRef context = cbm->getContext(); + + if (event->getResult()) { + LogDebug("result success"); + cbm->callOnSuccess(); + return; + } + LogDebug("result fail"); + + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagMifareClassicTransferPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + if (!cbm) { + LogDebug("no callback manager"); + return; + } + if (event->getResult()) { + LogDebug("result success"); + cbm->callOnSuccess(); + return; + } + LogDebug("result fail"); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagMifareClassicRestorePtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + JSContextRef context = cbm->getContext(); + + if (event->getResult()) { + LogDebug("result success"); + cbm->callOnSuccess(); + return; + } + LogDebug("result fail"); + + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagMifareUltraReadPagePtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + Try { + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + JSContextRef context = cbm->getContext(); + if (event->getResult()) { + NFCConverter convert(context); + LogDebug("result success"); + cbm->callOnSuccess(convert.toJSValueRef(event->getReadPageResult())); + return; + } + LogDebug("result fail"); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } Catch (ConversionException) { + LogError("Conversion exception while processing EventTagMifareUltraReadPage"); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } Catch (Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + JSValueRef errorObject = JSTizenExceptionFactory::makeErrorObject(cbm->getContext(), JSTizenException::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagMifareUltraWritePagePtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + JSContextRef context = cbm->getContext(); + + if (event->getResult()) { + LogDebug("result success"); + cbm->callOnSuccess(); + return; + } + LogDebug("result fail"); + + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTargetActionSendPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + JSContextRef context = cbm->getContext(); + + if (event->getResult()) { + LogDebug("result success"); + cbm->callOnSuccess(); + return; + } + LogDebug("result fail"); + + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::UNKNOWN_ERROR,"Unknown Error")); +} + +void NFCResponseDispatcher::onAnswerReceived(const EventTargetActionReceivePtr &event) +{ + LogDebug("onAnswerReceived Enter"); + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast(event->getPrivateData()); + + Try { + if (!cbm) { + LogDebug("no callback manager"); + return; + } + + JSContextRef context = cbm->getContext(); + + LogDebug("result success"); + cbm->callOnSuccess(JSNdefMessage::createJSObject(context, event->getReadNdefResult())); + } Catch (PlatformException) { + LogError("Platform can't create NdefMessage" << _rethrown_exception.GetMessage()); + } Catch (Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } +} + +} +} diff --git a/src/standards/Tizen/NFC/ResponseDispatcher.h b/src/standards/Tizen/NFC/ResponseDispatcher.h new file mode 100755 index 0000000..0a482e9 --- /dev/null +++ b/src/standards/Tizen/NFC/ResponseDispatcher.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTPLUGINS_TIZEN10_NFC_RESPONSEDISPATCHER_H_ +#define WRTPLUGINS_TIZEN10_NFC_RESPONSEDISPATCHER_H_ + +#include +#include +#include +#include +#include +#include +#include + +using namespace TizenApis::Api::NFC; +using namespace WrtDeviceApis::Commons; +namespace TizenApis { +namespace Tizen1_0 { + +typedef EventAnswerReceiver< EventTagActionRead > readNDEFAnswerReceiver; +typedef EventAnswerReceiver< EventTagActionWrite > writeNDEFAnswerReceiver; +typedef EventAnswerReceiver< EventTagActionTransceive > transceiveAnswerReceiver; +typedef EventAnswerReceiver< EventTagActionFormat > formatAnswerReceiver; + +typedef EventAnswerReceiver< EventTagMifareClassicAuthenticateWithKeyA > mifareClassicAuthenticateWithKeyAAnswerReceiver; +typedef EventAnswerReceiver< EventTagMifareClassicAuthenticateWithKeyB > mifareClassicAuthenticateWithKeyBAnswerReceiver; +typedef EventAnswerReceiver< EventTagMifareClassicReadBlock > mifareClassicReadBlockAnswerReceiver; +typedef EventAnswerReceiver< EventTagMifareClassicWriteBlock > mifareClassicWriteBlockAnswerReceiver; +typedef EventAnswerReceiver< EventTagMifareClassicIncrementBlockValue > mifareClassicIncrementBlockValueAnswerReceiver; +typedef EventAnswerReceiver< EventTagMifareClassicDecrementBlockValue > mifareClassicDecrementBlockValueAnswerReceiver; +typedef EventAnswerReceiver< EventTagMifareClassicTransfer > mifareClassicTransferAnswerReceiver; +typedef EventAnswerReceiver< EventTagMifareClassicRestore > mifareClassicRestoreAnswerReceiver; + +typedef EventAnswerReceiver< EventTagMifareUltraReadPage > mifareUltraReadPageAnswerReceiver; +typedef EventAnswerReceiver< EventTagMifareUltraWritePage > mifareUltraWritePageAnswerReceiver; + +typedef EventAnswerReceiver< EventTargetActionSend > TargetSendNdefAnswerReceiver; +typedef EventListener< EventTargetActionReceive > TargetReceiveNdefListener; + +class NFCResponseDispatcher : + public readNDEFAnswerReceiver, + public writeNDEFAnswerReceiver, + public transceiveAnswerReceiver, + public formatAnswerReceiver, + public mifareClassicAuthenticateWithKeyAAnswerReceiver, + public mifareClassicAuthenticateWithKeyBAnswerReceiver, + public mifareClassicReadBlockAnswerReceiver, + public mifareClassicWriteBlockAnswerReceiver, + public mifareClassicIncrementBlockValueAnswerReceiver, + public mifareClassicDecrementBlockValueAnswerReceiver, + public mifareClassicTransferAnswerReceiver, + public mifareClassicRestoreAnswerReceiver, + public mifareUltraReadPageAnswerReceiver, + public mifareUltraWritePageAnswerReceiver, + public TargetSendNdefAnswerReceiver, + public TargetReceiveNdefListener + +{ +public: + static NFCResponseDispatcher& getInstance(); +private: + NFCResponseDispatcher(); + virtual ~NFCResponseDispatcher(); +protected: + void OnAnswerReceived(const EventTagActionReadPtr &event); + void OnAnswerReceived(const EventTagActionWritePtr &event); + void OnAnswerReceived(const EventTagActionTransceivePtr &event); + void OnAnswerReceived(const EventTagActionFormatPtr &event); + + void OnAnswerReceived(const EventTagMifareClassicAuthenticateWithKeyAPtr &event); + void OnAnswerReceived(const EventTagMifareClassicAuthenticateWithKeyBPtr &event); + void OnAnswerReceived(const EventTagMifareClassicReadBlockPtr &event); + void OnAnswerReceived(const EventTagMifareClassicWriteBlockPtr &event); + void OnAnswerReceived(const EventTagMifareClassicIncrementBlockValuePtr &event); + void OnAnswerReceived(const EventTagMifareClassicDecrementBlockValuePtr &event); + void OnAnswerReceived(const EventTagMifareClassicTransferPtr &event); + void OnAnswerReceived(const EventTagMifareClassicRestorePtr &event); + + void OnAnswerReceived(const EventTagMifareUltraReadPagePtr &event); + void OnAnswerReceived(const EventTagMifareUltraWritePagePtr &event); + + void OnAnswerReceived(const EventTargetActionSendPtr &event); + void onAnswerReceived(const EventTargetActionReceivePtr &event); +}; + +} +} + +#endif \ No newline at end of file diff --git a/src/standards/Tizen/NFC/config.xml b/src/standards/Tizen/NFC/config.xml new file mode 100755 index 0000000..3e0e749 --- /dev/null +++ b/src/standards/Tizen/NFC/config.xml @@ -0,0 +1,33 @@ + + + + libwrt-plugins-tizen-1.0-nfc.so + nfc.install.uri + SAMSUNG plugin group + SAMSUNG certificate authority + AAAABBBBCCCCDDDEEEE0000 + + + http://tizen.org/api/nfc + nfc.tag + nfc.p2p + nfc.se + + + + http://tizen.org/api/nfc.tag + nfc.tag + + + + http://tizen.org/api/nfc.p2p + nfc.p2p + + + + http://tizen.org/api/nfc.se + nfc.se + + + + diff --git a/src/standards/Tizen/NFC/plugin_config.cpp b/src/standards/Tizen/NFC/plugin_config.cpp new file mode 100755 index 0000000..cb20a27 --- /dev/null +++ b/src/standards/Tizen/NFC/plugin_config.cpp @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#include +#include +#include +#include +#include +#include "plugin_config.h" + +#define NFC_FEATURE_API "http://tizen.org/api/nfc" +#define NFC_FEATURE_API_TAG "http://tizen.org/api/nfc.tag" +#define NFC_FEATURE_API_P2P "http://tizen.org/api/nfc.p2p" +#define NFC_FEATURE_API_SE "http://tizen.org/api/nfc.se" + +#define NFC_DEVICE_CAP_TAG "nfc.tag" +#define NFC_DEVICE_CAP_P2P "nfc.p2p" +#define NFC_DEVICE_CAP_SE "nfc.se" + +namespace TizenApis { +namespace Tizen1_0 { + +const char* NFC_FUNCTION_API_TAG_FUNCS = "NFCTagFunctions"; +const char* NFC_FUNCTION_API_P2P_FUNCS = "NFCP2PFunctions"; +const char* NFC_FUNCTION_API_SE_FUNCS = "NFCSEFunctions"; +const char* NFC_FUNCTION_API_TAG_P2P_FUNCS = "NFCTagP2PFunctions"; + +static WrtDeviceApis::Commons::FunctionMapping createNFCFunctions(); + +static WrtDeviceApis::Commons::FunctionMapping NFCFunctions = + createNFCFunctions(); + +DEFINE_FUNCTION_GETTER(NFC, NFCFunctions); + +static WrtDeviceApis::Commons::FunctionMapping createNFCFunctions() +{ + using namespace WrtDeviceApis::Commons; + + /** + * Device capabilities + */ + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_NFC_TAG, NFC_DEVICE_CAP_TAG); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_NFC_P2P, NFC_DEVICE_CAP_P2P); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_NFC_SE, NFC_DEVICE_CAP_SE); + + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_NFC_TAG); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_NFC_TAG, DEVICE_CAP_NFC_TAG); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_NFC_P2P); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_NFC_P2P, DEVICE_CAP_NFC_P2P); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_NFC_SE); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_NFC_SE, DEVICE_CAP_NFC_SE); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_NFC_TAG_P2P); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_NFC_TAG_P2P, DEVICE_CAP_NFC_TAG); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_NFC_TAG_P2P, DEVICE_CAP_NFC_P2P); + + /** + * API features + */ + ACE_CREATE_FEATURE(FEATURE_NFC, NFC_FEATURE_API); + ACE_CREATE_FEATURE(FEATURE_TAG, NFC_FEATURE_API_TAG); + ACE_CREATE_FEATURE(FEATURE_P2P, NFC_FEATURE_API_P2P); + ACE_CREATE_FEATURE(FEATURE_SE, NFC_FEATURE_API_SE); + + ACE_CREATE_FEATURE_LIST(NFC_FEATURES_NFC); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC, FEATURE_NFC); + + ACE_CREATE_FEATURE_LIST(NFC_FEATURES_NFC_TAG); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_TAG, FEATURE_TAG); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_TAG, FEATURE_NFC); + + ACE_CREATE_FEATURE_LIST(NFC_FEATURES_NFC_P2P); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_P2P, FEATURE_P2P); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_P2P, FEATURE_NFC); + + ACE_CREATE_FEATURE_LIST(NFC_FEATURES_NFC_SE); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_SE, FEATURE_SE); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_SE, FEATURE_NFC); + + ACE_CREATE_FEATURE_LIST(NFC_FEATURES_NFC_TAG_P2P); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_TAG_P2P, FEATURE_TAG); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_TAG_P2P, FEATURE_P2P); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_TAG_P2P, FEATURE_NFC); + + /** + * Functions + */ + FunctionMapping NFCFunctions; + + AceFunction nfcTagFuncs = ACE_CREATE_FUNCTION( + FUNCTION_NFC_TAG_FUNCTIONS, + NFC_FUNCTION_API_TAG_FUNCS, + NFC_FEATURES_NFC_TAG, + DEVICE_LIST_NFC_TAG); + + NFCFunctions.insert(std::make_pair( + NFC_FUNCTION_API_TAG_FUNCS, + nfcTagFuncs)); + + AceFunction nfcP2PFuncs = ACE_CREATE_FUNCTION( + FUNCTION_NFC_P2P_FUNCTIONS, + NFC_FUNCTION_API_P2P_FUNCS, + NFC_FEATURES_NFC_P2P, + DEVICE_LIST_NFC_P2P); + + NFCFunctions.insert(std::make_pair( + NFC_FUNCTION_API_P2P_FUNCS, + nfcP2PFuncs)); + + AceFunction nfcSEFuncs = ACE_CREATE_FUNCTION( + FUNCTION_NFC_SE_FUNCTIONS, + NFC_FUNCTION_API_SE_FUNCS, + NFC_FEATURES_NFC_SE, + DEVICE_LIST_NFC_SE); + + NFCFunctions.insert(std::make_pair( + NFC_FUNCTION_API_SE_FUNCS, + nfcSEFuncs)); + + AceFunction nfcTagP2PFuncs = ACE_CREATE_FUNCTION( + FUNCTION_NFC_TAG_P2P_FUNCTIONS, + NFC_FUNCTION_API_TAG_P2P_FUNCS, + NFC_FEATURES_NFC_TAG_P2P, + DEVICE_LIST_NFC_TAG_P2P); + + NFCFunctions.insert(std::make_pair( + NFC_FUNCTION_API_TAG_P2P_FUNCS, + nfcTagP2PFuncs)); + + + return NFCFunctions; +} +} // namespace Tizen1_0 +} // namespace TizenApis + +#undef NFC_FEATURE_API +#undef NFC_FEATURE_API_TAG +#undef NFC_FEATURE_API_P2P +#undef NFC_FEATURE_API_SE +#undef NFC_DEVICE_CAP_TAG +#undef NFC_DEVICE_CAP_P2P +#undef NFC_DEVICE_CAP_SE + diff --git a/src/standards/Tizen/NFC/plugin_config.h b/src/standards/Tizen/NFC/plugin_config.h new file mode 100755 index 0000000..d250700 --- /dev/null +++ b/src/standards/Tizen/NFC/plugin_config.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _NFC_PLUGIN_CONFIG_H_ +#define _NFC_PLUGIN_CONFIG_H_ + +#include + +namespace TizenApis { +namespace Tizen1_0 { + +extern const char* NFC_FUNCTION_API_TAG_FUNCS; +extern const char* NFC_FUNCTION_API_P2P_FUNCS; +extern const char* NFC_FUNCTION_API_SE_FUNCS; +extern const char* NFC_FUNCTION_API_TAG_P2P_FUNCS; + +DECLARE_FUNCTION_GETTER(NFC); + +#define NFC_CHECK_ACCESS(globalContext, functionName) \ + aceCheckAccess >( \ + globalContext, \ + getNFCFunctionData, \ + functionName) +} +} + +#endif // _NFC_PLUGIN_CONFIG_H_ \ No newline at end of file diff --git a/src/standards/Tizen/NFC/plugin_initializer.cpp b/src/standards/Tizen/NFC/plugin_initializer.cpp new file mode 100755 index 0000000..5aae9e4 --- /dev/null +++ b/src/standards/Tizen/NFC/plugin_initializer.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "JSNFCManager.h" + +void on_widget_start_callback(int widgetId, JavaScriptContext context, const engine_interface_t *interface) +{ + LogDebug("[TIZEN1.0\\NFC ] on_widget_start_callback (" << widgetId << ")"); +} + +void on_widget_stop_callback(int widgetId) +{ + LogDebug("[TIZEN1.0\\NFC ] on_widget_stop_callback (" << widgetId << ")"); +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, "nfc", TizenApis::Tizen1_0::JSNFCManager::getClassRef(), NULL) +PLUGIN_CLASS_MAP_END + diff --git a/src/standards/Tizen/Sensors/CMakeLists.txt b/src/standards/Tizen/Sensors/CMakeLists.txt new file mode 100755 index 0000000..a8537a2 --- /dev/null +++ b/src/standards/Tizen/Sensors/CMakeLists.txt @@ -0,0 +1,26 @@ +set(TARGET_NAME "wrt-plugins-tizen-1.0-sensors") + +pkg_search_module(system REQUIRED capi-system-sensor) + +include_directories(${system_INCLUDE_DIRS}) + +set(SRCS + JSSensor.cpp + JSSensorDataEvent.cpp + JSSensorError.cpp + JSSensorManager.cpp + JSSensorRequest.cpp + JSSensorConnection.cpp + JSSensorData.cpp + SensorType.cpp + plugin_initializer.cpp +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMON} + ${system_LIBRARIES} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION tizen-1.0-sensors) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION tizen-1.0-sensors) diff --git a/src/standards/Tizen/Sensors/JSSensor.cpp b/src/standards/Tizen/Sensors/JSSensor.cpp new file mode 100644 index 0000000..ddcdbd8 --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensor.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include "JSSensor.h" + +#include + +#undef LOG_TAG +#define LOG_TAG "TIZEN_SENSOR" + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassRef JSSensor::m_jsClassRef = NULL; + +JSClassDefinition JSSensor::m_jsClassInfo = { + 0, + kJSClassAttributeNone, + "Sensor", + NULL, + NULL, + NULL, + initialize, + finalize, + NULL, //hasProperty + NULL, //getProperty + NULL, //setProperty + NULL, //deleteProperty + NULL, //getPropertyNames + NULL, + NULL, // constructor + hasInstance, + NULL +}; + +const JSClassRef JSSensor::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSensor::getClassInfo() +{ + return &m_jsClassInfo; +} + +void JSSensor::initialize(JSContextRef ctx, JSObjectRef object) +{ +} + +void JSSensor::finalize(JSObjectRef object) +{ +} + +bool JSSensor::hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Sensors/JSSensor.h b/src/standards/Tizen/Sensors/JSSensor.h new file mode 100644 index 0000000..a0f04fa --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensor.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** +* @file JSSensor.h +* @author Pius Lee (pius.lee@samsung.com) +* @version 0.1 +*/ + +#ifndef _WRTPLUGINS_TIZEN_JS_SENSOR_ +#define _WRTPLUGINS_TIZEN_JS_SENSOR_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +class JSSensor { +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + static const JSObjectRef getSensor(sensor_type_e sensor); + + std::string type; + std::string name; + sensor_type_e typeId; + +protected: + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + +private: + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; +}; + +} // Tizen1_0 +} // TizenApis + +#endif diff --git a/src/standards/Tizen/Sensors/JSSensorConnection.cpp b/src/standards/Tizen/Sensors/JSSensorConnection.cpp new file mode 100755 index 0000000..9b8be6c --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensorConnection.cpp @@ -0,0 +1,917 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "JSSensorManager.h" +#include "JSSensorConnection.h" +#include "JSSensorData.h" +#include "JSSensorDataEvent.h" +#include "JSSensorError.h" +#include "SensorType.h" + +#include + +#undef LOG_TAG +#define LOG_TAG "TIZEN_SENSOR" + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +struct SensorConnection { + sensor_type_e type; + int status; + sensor_h handle; + bool started; + JSContextRef ctx; + + double interval; + double threshold; + + JSObjectRef sensor; + JSObjectRef error; + + JSObjectRef onerror; + JSObjectRef onsensordata; + JSObjectRef onstatuschange; + JSObjectRef oncalibneed; + + map< int, vector > listeners; + JSObjectRef jsobj; +}; + +enum { + SENSOR_LISTENER_ERROR, + SENSOR_LISTENER_DATA, + SENSOR_LISTENER_STATUS, + SENSOR_LISTENER_CALIB +}; + +struct FireArgs { + struct SensorConnection* scon; + int listenerType; + JSObjectRef event; +}; + +static void processEvent(JSContextRef ctx, struct SensorConnection* sc, int listenerType, JSObjectRef event) +{ + if(listenerType < SENSOR_LISTENER_ERROR || listenerType > SENSOR_LISTENER_CALIB){ + return; + } + if(sc != NULL){ + + if(event != NULL){ + JSStringRef pname_target = JSStringCreateWithUTF8CString("target"); + JSStringRef pname_currentTarget = JSStringCreateWithUTF8CString("currentTarget"); + JSObjectSetProperty(ctx, event, pname_target, sc->jsobj, kJSPropertyAttributeNone, NULL); + JSObjectSetProperty(ctx, event, pname_currentTarget, sc->jsobj, kJSPropertyAttributeNone, NULL); + JSStringRelease(pname_target); + JSStringRelease(pname_currentTarget); + } + + JSObjectRef pfunc = NULL; + switch(listenerType){ + case SENSOR_LISTENER_ERROR: + pfunc = sc->onerror; + break; + case SENSOR_LISTENER_DATA: + pfunc = sc->onsensordata; + break; + case SENSOR_LISTENER_STATUS: + pfunc = sc->onstatuschange; + break; + case SENSOR_LISTENER_CALIB: + pfunc = sc->oncalibneed; + break; + default: + break; + } + + if(pfunc != NULL){ + if(event == NULL){ + JSObjectCallAsFunction(ctx, pfunc, sc->jsobj, 0, NULL, NULL); + } + else{ + JSValueRef args[] = {event}; + JSObjectCallAsFunction(ctx, pfunc, sc->jsobj, 1, args, NULL); + } + } + + if(event == NULL){ + for(unsigned int i=0; ilisteners[listenerType].size(); i++){ + JSValueRef jsv = sc->listeners[listenerType][i]; + JSObjectRef func = JSValueToObject(ctx, jsv, NULL); + if(func != NULL) + JSObjectCallAsFunction(ctx, func, sc->jsobj, 0, NULL, NULL); + } + + } + else{ + JSValueRef args[] = {event}; + for(unsigned int i=0; ilisteners[listenerType].size(); i++){ + JSValueRef jsv = sc->listeners[listenerType][i]; + JSObjectRef func = JSValueToObject(ctx, jsv, NULL); + JSObjectCallAsFunction(ctx, func, sc->jsobj, 1, args, NULL); + } + } + } +} + +static gboolean afterFireProcess(gpointer user_data) +{ + struct FireArgs* args = (struct FireArgs*)user_data; + + JSContextRef ctx = JSSensorManager::gCtx; + struct SensorConnection* sc = args->scon; + int listenerType = args->listenerType; + JSObjectRef event = args->event; + + processEvent(ctx, sc, listenerType, event); + + delete args; + + return false; +} + +static void fireEvent(struct SensorConnection* sc, int listenerType, JSObjectRef event) +{ + struct FireArgs* args = new FireArgs; + args->scon = sc; + args->listenerType = listenerType; + args->event = event; + + g_idle_add_full(G_PRIORITY_HIGH_IDLE, afterFireProcess, args, NULL); +} + +static void addListener(JSContextRef ctx, struct SensorConnection* sc, int listenerType, JSValueRef func) +{ + if(sc != NULL){ + for(unsigned int i=0; ilisteners[listenerType].size(); i++){ + if(JSValueIsEqual(ctx, sc->listeners[listenerType][i], func, NULL)){ + return; + } + } + JSValueProtect(ctx, func); + sc->listeners[listenerType].push_back(func); + } +} +static void removeListener(JSContextRef ctx, struct SensorConnection* sc, int listenerType, JSValueRef func) +{ + if(sc != NULL){ + for(unsigned int i=0; ilisteners[listenerType].size(); i++){ + if(JSValueIsEqual(ctx, sc->listeners[listenerType][i], func, NULL)){ + sc->listeners[listenerType].erase(sc->listeners[listenerType].begin() + i); + JSValueUnprotect(ctx, func); + break; + } + } + } +} + +JSClassRef JSSensorConnection::m_jsClassRef = NULL; + +JSClassDefinition JSSensorConnection::m_jsClassInfo = { + 0, + kJSClassAttributeNone, + "SensorConnection", + NULL, + NULL, + m_function, + initialize, + finalize, + NULL, //hasProperty, + JSSensorConnection::getProperty, //getProperty, + JSSensorConnection::setProperty, //setProperty, + NULL, //deleteProperty + NULL, //getPropertyNames, + NULL, + JSSensorConnection::constructor, // constructor + hasInstance, + NULL +}; + +JSStaticFunction JSSensorConnection::m_function[] = { + { "read",JSSensorConnection::read,kJSPropertyAttributeNone }, + { "startWatch",JSSensorConnection::startWatch,kJSPropertyAttributeNone }, + { "endWatch",JSSensorConnection::endWatch,kJSPropertyAttributeNone }, + { "addEventListener",JSSensorConnection::addEventListener,kJSPropertyAttributeNone }, + { "removeEventListener",JSSensorConnection::removeEventListener,kJSPropertyAttributeNone }, + { "dispatchEvent",JSSensorConnection::dispatchEvent,kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef JSSensorConnection::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSensorConnection::getClassInfo() +{ + return &m_jsClassInfo; +} + +JSContextRef JSSensorConnection::m_globalCtx = NULL; + +void JSSensorConnection::initialize(JSContextRef ctx, JSObjectRef object) +{ + m_globalCtx = ctx; + SensorTypeUtil::getInstance(ctx); +} + +void JSSensorConnection::finalize(JSObjectRef object) +{ + struct SensorConnection* scon = (struct SensorConnection*) JSObjectGetPrivate(object); + + if(scon != NULL){ + if(scon->handle != NULL){ + sensor_destroy(scon->handle); + } + } +} + +bool JSSensorConnection::hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSSensorConnection::getProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + struct SensorConnection* scon = (struct SensorConnection*) JSObjectGetPrivate(object); + if(scon == NULL) + return NULL; + + if(JSStringIsEqualToUTF8CString(propertyName, "status")) { + JSStringRef status = NULL; + switch(scon->status) + { + case SENSOR_CON_NEW: + status = JSStringCreateWithUTF8CString("new"); + break; + case SENSOR_CON_OPEN: + status = JSStringCreateWithUTF8CString("open"); + break; + case SENSOR_CON_WATCHING: + status = JSStringCreateWithUTF8CString("watching"); + break; + case SENSOR_CON_DISCONNECTED: + status = JSStringCreateWithUTF8CString("disconnected"); + break; + case SENSOR_CON_ERROR: + status = JSStringCreateWithUTF8CString("error"); + break; + } + if(status != NULL){ + JSValueRef jsv = JSValueMakeString(ctx, status); + JSStringRelease(status); + return jsv; + } + return NULL; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "sensor")) { + if(scon->status == SENSOR_CON_NEW){ + *exception = JSDOMExceptionFactory::InvalidStateException.make(ctx); + return NULL; + } + + if(scon->sensor != NULL) + return scon->sensor; + return NULL; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "error")) { + if(scon->error == NULL){ + return JSValueMakeNull(ctx); + }else{ + return scon->error; + } + } + else if(JSStringIsEqualToUTF8CString(propertyName, "onerror")) { + return scon->onerror; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "onsensordata")) { + return scon->onsensordata; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "onstatuschange")) { + return scon->onstatuschange; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "oncalibneed")) { + return scon->oncalibneed; + } + + return NULL; +} + +bool JSSensorConnection::setProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + struct SensorConnection* scon = (struct SensorConnection*) JSObjectGetPrivate(object); + if(scon == NULL){ + return false; + } + + if(JSStringIsEqualToUTF8CString(propertyName, "status")) { + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "sensor")) { + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "error")) { + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "onerror")) { + if(scon->onerror != NULL){ + JSValueUnprotect(ctx, scon->onerror); + } + JSValueProtect(ctx, value); + return (scon->onerror = JSValueToObject(ctx, value, NULL)) != NULL; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "onsensordata")) { + if(scon->onsensordata != NULL){ + JSValueUnprotect(ctx, scon->onsensordata); + } + JSValueProtect(ctx, value); + return (scon->onsensordata = JSValueToObject(ctx, value, NULL)) != NULL; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "onstatuschange")) { + if(scon->onstatuschange != NULL){ + JSValueUnprotect(ctx, scon->onstatuschange); + } + JSValueProtect(ctx, value); + return (scon->onstatuschange = JSValueToObject(ctx, value, NULL)) != NULL; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "oncalibneed")) { + if(scon->oncalibneed != NULL){ + JSValueUnprotect(ctx, scon->oncalibneed); + } + JSValueProtect(ctx, value); + return (scon->oncalibneed = JSValueToObject(ctx, value, NULL)) != NULL; + } + + return false; +} + +static void throwError(struct SensorConnection* scon, const char* msg, int code) +{ + JSContextRef ctx = JSSensorManager::gCtx; + scon->error = JSSensorError::makeSensorError(ctx, msg, code); + fireEvent(scon, SENSOR_LISTENER_ERROR, scon->error); +} + +static gboolean connect_sensor(gpointer user_data) +{ + JSContextRef ctx = JSSensorManager::gCtx; + struct SensorConnection* scon = (struct SensorConnection*) user_data; + + if(scon == NULL){ + throwError(scon, "Unknown error", JSSensorError::UNKNOWN_ERROR); + return false; + } + + JSObjectRef sensor = SensorTypeUtil::getInstance(ctx)->getSensor(ctx, (sensor_type_e)scon->type); + JSStringRef pname_sensor = JSStringCreateWithUTF8CString("sensor"); + JSObjectSetProperty(ctx, scon->jsobj, pname_sensor, sensor, kJSPropertyAttributeReadOnly, NULL); + JSStringRelease(pname_sensor); + + + int err = sensor_create(&scon->handle); + if(err < 0) { + throwError(scon, "Connect fail", JSSensorError::CONNECT_ERROR); + return false; + } + scon->status = SENSOR_CON_OPEN; + scon->sensor = SensorTypeUtil::makeSensor(ctx, scon->type); + fireEvent( scon, SENSOR_LISTENER_STATUS, NULL); + + return false; +} + +JSObjectRef JSSensorConnection::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + char buf[64]; + char buf2[64]; + int type; + if(argumentCount < 1){ + *exception = JSDOMExceptionFactory::InvalidValuesException.make(ctx); + return NULL; + } + + if(JSValueIsString(ctx, arguments[0])){ + JSStringRef jss_type = JSValueToStringCopy(ctx, arguments[0], NULL); + JSStringGetUTF8CString(jss_type, buf, 64); + JSStringRelease(jss_type); + type = SensorTypeUtil::modifyType(buf); + } + else if(JSValueIsObject(ctx, arguments[0])){ + JSObjectRef sensorOption = JSValueToObject(ctx, arguments[0], NULL); + JSStringRef pname_type = JSStringCreateWithUTF8CString("type"); + JSStringRef pname_name = JSStringCreateWithUTF8CString("name"); + JSValueRef jsv_type = JSObjectGetProperty(ctx, sensorOption, pname_type, NULL); + JSValueRef jsv_name = JSObjectGetProperty(ctx, sensorOption, pname_name, NULL); + JSStringRelease(pname_type); + JSStringRelease(pname_name); + + if(jsv_type == NULL || jsv_name == NULL){ + *exception = JSDOMExceptionFactory::InvalidValuesException.make(ctx); + return NULL; + } + + JSStringRef jss_type = JSValueToStringCopy(ctx, jsv_type, NULL); + JSStringRef jss_name = JSValueToStringCopy(ctx, jsv_name, NULL); + JSStringGetUTF8CString(jss_type, buf, 64); + JSStringGetUTF8CString(jss_name, buf2, 64); + JSStringRelease(jss_type); + JSStringRelease(jss_name); + + type = SensorTypeUtil::modifyType(buf, buf2); + } + else{ + *exception = JSDOMExceptionFactory::InvalidValuesException.make(ctx); + return NULL; + } + if(type < 0){ + *exception = JSDOMExceptionFactory::InvalidValuesException.make(ctx); + return NULL; + } + + + JSClassRef jsCls = getClassRef(); + + struct SensorConnection* scon = new SensorConnection; + JSObjectRef obj = JSObjectMake(ctx, jsCls, scon); + + scon->listeners[SENSOR_LISTENER_ERROR] = vector(); + scon->listeners[SENSOR_LISTENER_STATUS] = vector(); + scon->listeners[SENSOR_LISTENER_DATA] = vector(); + scon->listeners[SENSOR_LISTENER_CALIB] = vector(); + + scon->handle = NULL; + scon->ctx = ctx; + scon->status = SENSOR_CON_NEW; + scon->type = (sensor_type_e)type; + scon->started = false; + scon->interval = 0; + scon->threshold = 0; + scon->jsobj = obj; + scon->error = NULL; + scon->onerror = NULL; + scon->onsensordata = NULL; + scon->onstatuschange = NULL; + scon->oncalibneed = NULL; + + fireEvent( scon, SENSOR_LISTENER_STATUS, NULL); + + g_idle_add_full(G_PRIORITY_HIGH_IDLE, connect_sensor, scon, NULL); + return obj; +} + +static void sensor_cb_accelerometer(sensor_data_accuracy_e accuracy, float x, float y, float z, void* ud) +{ + JSContextRef ctx = JSSensorManager::gCtx; + struct SensorConnection* scon = (struct SensorConnection*) ud; + if(accuracy < SENSOR_DATA_ACCURACY_UNDEFINED || accuracy > SENSOR_DATA_ACCURACY_VERYGOOD){ + accuracy = SENSOR_DATA_ACCURACY_UNDEFINED; + } + + JSSensorDataEvent* data = new JSSensorDataEvent(JSSENSOR_REASON_WATCH, scon->type); + data->set(accuracy, g_get_monotonic_time(), x, y, z); + + processEvent(ctx, scon, SENSOR_LISTENER_DATA, data->makeJSObj(ctx)); +} +static void sensor_cb_magnetic(sensor_data_accuracy_e accuracy, float x, float y, float z, void* ud) +{ + JSContextRef ctx = JSSensorManager::gCtx; + struct SensorConnection* scon = (struct SensorConnection*) ud; + if(accuracy < SENSOR_DATA_ACCURACY_UNDEFINED || accuracy > SENSOR_DATA_ACCURACY_VERYGOOD){ + accuracy = SENSOR_DATA_ACCURACY_UNDEFINED; + } + + JSSensorDataEvent* data = new JSSensorDataEvent(JSSENSOR_REASON_WATCH, scon->type); + data->set(accuracy, g_get_monotonic_time(), x, y, z); + processEvent(ctx, scon, SENSOR_LISTENER_DATA, data->makeJSObj(ctx)); +} +static void sensor_cb_orientation(sensor_data_accuracy_e accuracy, float alpha, float beta, float gamma, void* ud) +{ + JSContextRef ctx = JSSensorManager::gCtx; + struct SensorConnection* scon = (struct SensorConnection*) ud; + if(accuracy < SENSOR_DATA_ACCURACY_UNDEFINED || accuracy > SENSOR_DATA_ACCURACY_VERYGOOD){ + accuracy = SENSOR_DATA_ACCURACY_UNDEFINED; + } + + JSSensorDataEvent* data = new JSSensorDataEvent(JSSENSOR_REASON_WATCH, scon->type); + data->set(accuracy, g_get_monotonic_time(), alpha, beta, gamma); + processEvent(ctx, scon, SENSOR_LISTENER_DATA, data->makeJSObj(ctx)); +} +static void sensor_cb_gyroscope(sensor_data_accuracy_e accuracy, float x, float y, float z, void* ud) +{ + JSContextRef ctx = JSSensorManager::gCtx; + struct SensorConnection* scon = (struct SensorConnection*) ud; + if(accuracy < SENSOR_DATA_ACCURACY_UNDEFINED || accuracy > SENSOR_DATA_ACCURACY_VERYGOOD){ + accuracy = SENSOR_DATA_ACCURACY_UNDEFINED; + } + + JSSensorDataEvent* data = new JSSensorDataEvent(JSSENSOR_REASON_WATCH, scon->type); + data->set(accuracy, g_get_monotonic_time(), x, y, z); + processEvent(ctx, scon, SENSOR_LISTENER_DATA, data->makeJSObj(ctx)); +} +static void sensor_cb_light(sensor_data_accuracy_e accuracy, int level, void* ud) +{ + JSContextRef ctx = JSSensorManager::gCtx; + struct SensorConnection* scon = (struct SensorConnection*) ud; + + if(scon->threshold >= 0 && level != scon->threshold){ + return; + } + + JSSensorDataEvent* data = new JSSensorDataEvent(JSSENSOR_REASON_WATCH, scon->type); + data->set(accuracy, g_get_monotonic_time(), level); + processEvent(ctx, scon, SENSOR_LISTENER_DATA, data->makeJSObj(ctx)); +} +static void sensor_cb_proximity(bool is_near, void* ud) +{ + JSContextRef ctx = JSSensorManager::gCtx; + struct SensorConnection* scon = (struct SensorConnection*) ud; + + if(scon->threshold >= 0 && is_near != scon->threshold){ + return; + } + + JSSensorDataEvent* data = new JSSensorDataEvent(JSSENSOR_REASON_WATCH, scon->type); + data->set(SENSOR_DATA_ACCURACY_UNDEFINED, g_get_monotonic_time(), is_near); + processEvent(ctx, scon, SENSOR_LISTENER_DATA, data->makeJSObj(ctx)); +} +static void sensor_cb_calibration(void* ud) +{ + JSContextRef ctx = JSSensorManager::gCtx; + struct SensorConnection* scon = (struct SensorConnection*) ud; + processEvent(ctx, scon, SENSOR_LISTENER_CALIB, NULL); +} + +JSValueRef JSSensorConnection::read(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + struct SensorConnection* scon = (struct SensorConnection*) JSObjectGetPrivate(thisObject); + if(scon == NULL) + return JSDOMExceptionFactory::InvalidValuesException.make(ctx, exception); + + if(scon->status != SENSOR_CON_OPEN && scon->status != SENSOR_CON_WATCHING){ + return JSDOMExceptionFactory::InvalidStateException.make(ctx, exception); + } + + bool started = false; + float x, y, z; + int level; + sensor_data_accuracy_e acc; + JSSensorDataEvent* data = new JSSensorDataEvent(JSSENSOR_REASON_READ, scon->type); + if(scon->status != SENSOR_CON_WATCHING){ + sensor_start(scon->handle, scon->type); + started = true; + } + switch((int)scon->type) + { + case SENSOR_ACCELEROMETER: + sensor_accelerometer_read_data(scon->handle, &acc, &x, &y, &z); + data->set(acc, g_get_monotonic_time(), x, y, z); + break; + case SENSOR_MAGNETIC: + sensor_magnetic_read_data(scon->handle, &acc, &x, &y, &z); + data->set(acc, g_get_monotonic_time(), x, y, z); + break; + case SENSOR_ORIENTATION: + sensor_orientation_read_data(scon->handle, &acc, &x, &y, &z); + data->set(acc, g_get_monotonic_time(), x, y, z); + break; + case SENSOR_GYROSCOPE: + sensor_gyroscope_read_data(scon->handle, &acc, &x, &y, &z); + data->set(acc, g_get_monotonic_time(), x, y, z); + break; + case SENSOR_LIGHT: + sensor_light_read_data(scon->handle, &acc, &level); + data->set(acc, g_get_monotonic_time(), level); + break; + case SENSOR_PROXIMITY: + return JSDOMExceptionFactory::NotSupportedException.make(ctx, exception); + break; + + default: + return JSDOMExceptionFactory::NotSupportedException.make(ctx, exception); + } + if(started){ + sensor_stop(scon->handle, scon->type); + started = false; + } + processEvent(ctx, scon, SENSOR_LISTENER_DATA, data->makeJSObj(ctx)); + + return JSValueMakeUndefined(ctx); +} + +static gboolean registerAndStart(gpointer user_data) +{ + struct SensorConnection* scon = (struct SensorConnection*) user_data; + + int err; + switch(scon->type){ + case SENSOR_ACCELEROMETER: + err = sensor_accelerometer_set_cb(scon->handle, (int)scon->interval, sensor_cb_accelerometer, scon); + if(err <0) { + throwError(scon, "Watching fail", JSSensorError::WATCH_ERROR); + return false; + } + err = sensor_start(scon->handle, SENSOR_ACCELEROMETER); + if(err <0) { + sensor_accelerometer_unset_cb(scon->handle); + throwError(scon, "Watching fail", JSSensorError::WATCH_ERROR); + return false; + } + break; + case SENSOR_MAGNETIC: + err = sensor_magnetic_set_cb(scon->handle, (int)scon->interval, sensor_cb_magnetic, scon); + if(err <0) { + throwError(scon, "Watching fail", JSSensorError::WATCH_ERROR); + return false; + } + err = sensor_magnetic_set_calibration_cb(scon->handle, sensor_cb_calibration, scon); + if(err <0) { + sensor_magnetic_unset_cb(scon->handle); + throwError(scon, "Calibration watching fail", JSSensorError::WATCH_ERROR); + return false; + } + err = sensor_start(scon->handle, SENSOR_MAGNETIC); + if(err <0) { + sensor_magnetic_unset_cb(scon->handle); + sensor_magnetic_unset_calibration_cb(scon->handle); + throwError(scon, "Watching fail", JSSensorError::WATCH_ERROR); + return false; + } + break; + case SENSOR_ORIENTATION: + err = sensor_orientation_set_cb(scon->handle, (int)scon->interval, sensor_cb_orientation, scon); + if(err <0) { + throwError(scon, "Watching fail", JSSensorError::WATCH_ERROR); + return false; + } + err = sensor_start(scon->handle, SENSOR_ORIENTATION); + if(err <0) { + sensor_orientation_unset_cb(scon->handle); + throwError(scon, "Watching fail", JSSensorError::WATCH_ERROR); + return false; + } + break; + case SENSOR_GYROSCOPE: + err = sensor_gyroscope_set_cb(scon->handle, (int)scon->interval, sensor_cb_gyroscope, scon); + if(err <0) { + throwError(scon, "Watching fail", JSSensorError::WATCH_ERROR); + return false; + } + err = sensor_start(scon->handle, SENSOR_GYROSCOPE); + if(err <0) { + sensor_gyroscope_unset_cb(scon->handle); + throwError(scon, "Watching fail", JSSensorError::WATCH_ERROR); + return false; + } + break; + case SENSOR_LIGHT: + err = sensor_light_set_cb(scon->handle, (int)scon->interval, sensor_cb_light, scon); + if(err <0) { + throwError(scon, "Watching fail", JSSensorError::WATCH_ERROR); + return false; + } + err = sensor_start(scon->handle, SENSOR_LIGHT); + if(err <0) { + sensor_light_unset_cb(scon->handle); + throwError(scon, "Watching fail", JSSensorError::WATCH_ERROR); + return false; + } + break; + case SENSOR_PROXIMITY: + err = sensor_proximity_set_cb(scon->handle, sensor_cb_proximity, scon); + if(err <0) { + throwError(scon, "Watching fail", JSSensorError::WATCH_ERROR); + return false; + } + err = sensor_start(scon->handle, SENSOR_PROXIMITY); + if(err <0) { + sensor_proximity_unset_cb(scon->handle); + throwError(scon, "Calibration watching fail", JSSensorError::WATCH_ERROR); + return false; + } + break; + default: + throwError(scon, "Unknown error", JSSensorError::UNKNOWN_ERROR); + return false; + } + + scon->status = SENSOR_CON_WATCHING; + fireEvent( scon, SENSOR_LISTENER_STATUS, NULL); + + return false; +} + +JSValueRef JSSensorConnection::startWatch(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + struct SensorConnection* scon = (struct SensorConnection*) JSObjectGetPrivate(thisObject); + if(scon == NULL) + return JSDOMExceptionFactory::InvalidValuesException.make(ctx, exception); + + if(scon->status != SENSOR_CON_OPEN){ + return JSDOMExceptionFactory::InvalidStateException.make(ctx, exception); + } + + if(argumentCount > 0){ + double threshold = -1, interval = 0; + if(!JSValueIsObject(ctx, arguments[0])) + return JSDOMExceptionFactory::InvalidValuesException.make(ctx, exception); + + JSObjectRef watchOption = JSValueToObject(ctx, arguments[0], NULL); + JSStringRef pname_threshold = JSStringCreateWithUTF8CString("threshold"); + JSStringRef pname_interval = JSStringCreateWithUTF8CString("interval"); + if(JSObjectHasProperty(ctx, watchOption, pname_threshold)){ + JSValueRef jsv_threshold = JSObjectGetProperty(ctx, watchOption, pname_threshold, NULL); + threshold = JSValueToNumber(ctx, jsv_threshold, NULL); + } + if(JSObjectHasProperty(ctx, watchOption, pname_interval)){ + JSValueRef jsv_interval = JSObjectGetProperty(ctx, watchOption, pname_interval, NULL); + interval = JSValueToNumber(ctx, jsv_interval, NULL); + } + JSStringRelease(pname_threshold); + JSStringRelease(pname_interval); + scon->threshold = threshold; + scon->interval = interval; + }else{ + scon->threshold = -1; + scon->interval = 0; + } + +// JSSensorDataEvent::setReason(ctx, scon->eventData, JSSENSOR_REASON_WATCH); + + g_idle_add_full(G_PRIORITY_HIGH_IDLE, registerAndStart, scon, NULL); + + return JSValueMakeUndefined(ctx); +} + + +static gboolean deregisterandstop(gpointer user_data) +{ + struct SensorConnection* scon = (struct SensorConnection*) user_data; + int err = 0; + switch(scon->type){ + case SENSOR_ACCELEROMETER: + err += sensor_stop(scon->handle, SENSOR_ACCELEROMETER); + err += sensor_accelerometer_unset_cb(scon->handle); + break; + case SENSOR_MAGNETIC: + err += sensor_stop(scon->handle, SENSOR_MAGNETIC); + err += sensor_magnetic_unset_cb(scon->handle); + err += sensor_magnetic_unset_calibration_cb(scon->handle); + break; + case SENSOR_ORIENTATION: + err += sensor_stop(scon->handle, SENSOR_ORIENTATION); + err += sensor_orientation_unset_cb(scon->handle); + break; + case SENSOR_GYROSCOPE: + err += sensor_stop(scon->handle, SENSOR_GYROSCOPE); + err += sensor_gyroscope_unset_cb(scon->handle); + break; + case SENSOR_LIGHT: + err += sensor_stop(scon->handle, SENSOR_LIGHT); + err += sensor_light_unset_cb(scon->handle); + break; + case SENSOR_PROXIMITY: + err += sensor_stop(scon->handle, SENSOR_PROXIMITY); + err += sensor_proximity_unset_cb(scon->handle); + break; + default: + throwError(scon, "Unknown error", JSSensorError::UNKNOWN_ERROR); + return false; + } + if(err <0) { + throwError(scon, "End watching fail", JSSensorError::END_WATCH_ERROR); + return false; + } + + scon->status = SENSOR_CON_OPEN; + fireEvent( scon, SENSOR_LISTENER_STATUS, NULL); + + return false; +} + +JSValueRef JSSensorConnection::endWatch(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + struct SensorConnection* scon = (struct SensorConnection*) JSObjectGetPrivate(thisObject); + if(scon == NULL) + return JSDOMExceptionFactory::InvalidValuesException.make(ctx, exception); + + if(scon->status != SENSOR_CON_WATCHING){ + return JSDOMExceptionFactory::InvalidStateException.make(ctx, exception); + } + + g_idle_add_full(G_PRIORITY_HIGH_IDLE, deregisterandstop, scon, NULL); + + return JSValueMakeUndefined(ctx); +} + +static int detectListenerType(std::string& strType) +{ + if(strType.compare("error") == 0){ + return SENSOR_LISTENER_ERROR; + } + else if(strType.compare("sensordata") == 0){ + return SENSOR_LISTENER_DATA; + } + else if(strType.compare("statuschange") == 0){ + return SENSOR_LISTENER_STATUS; + } + else if(strType.compare("calibneed") == 0){ + return SENSOR_LISTENER_CALIB; + } + return -1; +} + +JSValueRef JSSensorConnection::addEventListener(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + struct SensorConnection* scon = (struct SensorConnection*) JSObjectGetPrivate(thisObject); + Converter converter(ctx); + + if( argumentCount < 2 ) + return JSDOMExceptionFactory::InvalidValuesException.make(ctx, exception); + + std::string typeStr = converter.toString(arguments[0]); + int type = detectListenerType(typeStr); + + if(type < 0){ + return JSDOMExceptionFactory::InvalidValuesException.make(ctx, exception); + } + + addListener(ctx, scon, type, arguments[1]); + + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSSensorConnection::removeEventListener(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + struct SensorConnection* scon = (struct SensorConnection*) JSObjectGetPrivate(thisObject); + Converter converter(ctx); + + if( argumentCount < 2 ) + return JSDOMExceptionFactory::InvalidValuesException.make(ctx, exception); + + std::string typeStr = converter.toString(arguments[0]); + int type = detectListenerType(typeStr); + + if(type < 0){ + return JSDOMExceptionFactory::InvalidValuesException.make(ctx, exception); + } + + removeListener(ctx, scon, type, arguments[1]); + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSSensorConnection::dispatchEvent(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + struct SensorConnection* scon = (struct SensorConnection*) JSObjectGetPrivate(thisObject); + Converter converter(ctx); + + if( argumentCount < 1 ) + return JSDOMExceptionFactory::InvalidValuesException.make(ctx, exception); + + JSObjectRef event = JSValueToObject(ctx, arguments[0], NULL); + JSStringRef jss_type = JSStringCreateWithUTF8CString("type"); + JSValueRef jsv_type = JSObjectGetProperty(ctx, event, jss_type, NULL); + JSStringRelease(jss_type); + + std::string typeStr = converter.toString(jsv_type); + int type = detectListenerType(typeStr); + + if(type < 0){ + return JSDOMExceptionFactory::InvalidValuesException.make(ctx, exception); + } + + fireEvent( scon, type, event); + + return JSValueMakeBoolean(ctx, true); +} + +} // Tizen1_0 +} // TizenApis + diff --git a/src/standards/Tizen/Sensors/JSSensorConnection.h b/src/standards/Tizen/Sensors/JSSensorConnection.h new file mode 100644 index 0000000..14497d0 --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensorConnection.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** +* @file JSSensorConnection.h +* @author Pius Lee (pius.lee@samsung.com) +* @version 0.1 +*/ + +#ifndef _WRTPLUGINS_TIZEN_JS_SENSOR_CONNECTION_ +#define _WRTPLUGINS_TIZEN_JS_SENSOR_CONNECTION_ + +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +enum { + SENSOR_CON_NEW, + SENSOR_CON_OPEN, + SENSOR_CON_WATCHING, + SENSOR_CON_DISCONNECTED, + SENSOR_CON_ERROR +}; + +class JSSensorConnection { +public: + static JSContextRef m_globalCtx; + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + +protected: + static void initialize(JSContextRef ctx, JSObjectRef object); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + static JSValueRef read(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef startWatch(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef endWatch(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + // Event Target + static JSValueRef addEventListener(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef removeEventListener(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef dispatchEvent(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef getProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static bool setProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception); + +private: + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + static JSStaticFunction m_function[]; +}; + +} // Tizen1_0 +} // TizenApis + +#endif diff --git a/src/standards/Tizen/Sensors/JSSensorData.cpp b/src/standards/Tizen/Sensors/JSSensorData.cpp new file mode 100755 index 0000000..698dae6 --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensorData.cpp @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include "JSSensorData.h" + +#include + +#undef LOG_TAG +#define LOG_TAG "TIZEN_SENSOR" + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassRef JSSensorData::m_jsClassRef = NULL; + +JSClassDefinition JSSensorData::m_jsClassInfo = { + 0, + kJSClassAttributeNone, + "Sensor", + NULL, + NULL, + NULL, + initialize, + finalize, + hasProperty, //hasProperty + getProperty, //getProperty + setProperty, //setProperty + NULL, //deleteProperty + getPropertyNames, //getPropertyNames + NULL, + NULL, // constructor + hasInstance, + NULL +}; + +const JSClassRef JSSensorData::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSensorData::getClassInfo() +{ + return &m_jsClassInfo; +} + +void JSSensorData::initialize(JSContextRef ctx, JSObjectRef object) +{ +} + +void JSSensorData::finalize(JSObjectRef object) +{ +} + +bool JSSensorData::hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +bool JSSensorData::hasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName) +{ + JSSensorData* data = (JSSensorData*)JSObjectGetPrivate(object); + if(data == NULL){ + return false; + } + switch(data->mType){ + case SENSOR_ACCELEROMETER: + case SENSOR_MAGNETIC: + case SENSOR_GYROSCOPE: + if(JSStringIsEqualToUTF8CString(propertyName, "x")){ + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "y")){ + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "z")){ + return true; + } + break; + case SENSOR_ORIENTATION: + if(JSStringIsEqualToUTF8CString(propertyName, "alpha")){ + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "beta")){ + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "gamma")){ + return true; + } + break; + case SENSOR_LIGHT: + if(JSStringIsEqualToUTF8CString(propertyName, "level")){ + return true; + } + break; + case SENSOR_PROXIMITY: + if(JSStringIsEqualToUTF8CString(propertyName, "near")){ + return true; + } + break; + default: + return false; + } + + return false; +} + +JSValueRef JSSensorData::getProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + JSSensorData* data = (JSSensorData*)JSObjectGetPrivate(object); + if(data == NULL){ + *exception = JSDOMExceptionFactory::InvalidValuesException.make(ctx); + return NULL; + } + + switch(data->mType){ + case SENSOR_ACCELEROMETER: + case SENSOR_MAGNETIC: + case SENSOR_GYROSCOPE: + if(JSStringIsEqualToUTF8CString(propertyName, "x")){ + return JSValueMakeNumber(ctx, data->mData.xyz[0]); + } + else if(JSStringIsEqualToUTF8CString(propertyName, "y")){ + return JSValueMakeNumber(ctx, data->mData.xyz[1]); + } + else if(JSStringIsEqualToUTF8CString(propertyName, "z")){ + return JSValueMakeNumber(ctx, data->mData.xyz[2]); + } + break; + case SENSOR_ORIENTATION: + if(JSStringIsEqualToUTF8CString(propertyName, "alpha")){ + return JSValueMakeNumber(ctx, data->mData.xyz[0]); + } + else if(JSStringIsEqualToUTF8CString(propertyName, "beta")){ + return JSValueMakeNumber(ctx, data->mData.xyz[1]); + } + else if(JSStringIsEqualToUTF8CString(propertyName, "gamma")){ + return JSValueMakeNumber(ctx, data->mData.xyz[2]); + } + break; + case SENSOR_LIGHT: + if(JSStringIsEqualToUTF8CString(propertyName, "level")){ + return JSValueMakeNumber(ctx, data->mData.level); + } + break; + case SENSOR_PROXIMITY: + if(JSStringIsEqualToUTF8CString(propertyName, "near")){ + return JSValueMakeBoolean(ctx, data->mData.near); + } + break; + default: + return NULL; + } + + return NULL; +} + +bool JSSensorData::setProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + JSSensorData* data = (JSSensorData*)JSObjectGetPrivate(object); + if(data == NULL){ + *exception = JSDOMExceptionFactory::InvalidValuesException.make(ctx); + return NULL; + } + switch(data->mType){ + case SENSOR_ACCELEROMETER: + case SENSOR_MAGNETIC: + case SENSOR_GYROSCOPE: + if(JSStringIsEqualToUTF8CString(propertyName, "x")){ + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "y")){ + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "z")){ + return true; + } + break; + case SENSOR_ORIENTATION: + if(JSStringIsEqualToUTF8CString(propertyName, "alpha")){ + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "beta")){ + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "gamma")){ + return true; + } + break; + case SENSOR_LIGHT: + if(JSStringIsEqualToUTF8CString(propertyName, "level")){ + return true; + } + break; + case SENSOR_PROXIMITY: + if(JSStringIsEqualToUTF8CString(propertyName, "near")){ + return true; + } + break; + default: + return false; + } + return false; +} +void JSSensorData::getPropertyNames(JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames) +{ + JSStringRef pname_x = NULL; + JSStringRef pname_y = NULL; + JSStringRef pname_z = NULL; + JSStringRef pname_alpha = NULL; + JSStringRef pname_beta = NULL; + JSStringRef pname_gamma = NULL; + JSStringRef pname_level = NULL; + JSStringRef pname_near = NULL; + JSSensorData* data = (JSSensorData*)JSObjectGetPrivate(object); + switch(data->mType){ + case SENSOR_ACCELEROMETER: + case SENSOR_MAGNETIC: + case SENSOR_GYROSCOPE: + pname_x = JSStringCreateWithUTF8CString("x"); + pname_y = JSStringCreateWithUTF8CString("y"); + pname_z = JSStringCreateWithUTF8CString("z"); + JSPropertyNameAccumulatorAddName(propertyNames, pname_x); + JSPropertyNameAccumulatorAddName(propertyNames, pname_y); + JSPropertyNameAccumulatorAddName(propertyNames, pname_z); + JSStringRelease(pname_x); + JSStringRelease(pname_y); + JSStringRelease(pname_z); + break; + case SENSOR_ORIENTATION: + pname_alpha = JSStringCreateWithUTF8CString("alpha"); + pname_beta = JSStringCreateWithUTF8CString("beta"); + pname_gamma = JSStringCreateWithUTF8CString("gamma"); + JSPropertyNameAccumulatorAddName(propertyNames, pname_alpha); + JSPropertyNameAccumulatorAddName(propertyNames, pname_beta); + JSPropertyNameAccumulatorAddName(propertyNames, pname_gamma); + JSStringRelease(pname_alpha); + JSStringRelease(pname_beta); + JSStringRelease(pname_gamma); + break; + case SENSOR_LIGHT: + pname_level = JSStringCreateWithUTF8CString("level"); + JSPropertyNameAccumulatorAddName(propertyNames, pname_level); + JSStringRelease(pname_level); + break; + case SENSOR_PROXIMITY: + pname_near = JSStringCreateWithUTF8CString("near"); + JSPropertyNameAccumulatorAddName(propertyNames, pname_near); + JSStringRelease(pname_near); + break; + default: + return; + } +} + +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Sensors/JSSensorData.h b/src/standards/Tizen/Sensors/JSSensorData.h new file mode 100755 index 0000000..79b29d3 --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensorData.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** +* @file JSSensorData.h +* @author Pius Lee (pius.lee@samsung.com) +* @version 0.1 +*/ + +#ifndef _WRTPLUGINS_TIZEN_JS_SENSORDATA_ +#define _WRTPLUGINS_TIZEN_JS_SENSORDATA_ + +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +union SensorData { + float xyz[3]; + int level; + bool near; +}; + +class JSSensorData { +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + JSSensorData(sensor_type_e type): mType(type){} + void set(float x, float y, float z) + { + mData.xyz[0] = x; + mData.xyz[1] = y; + mData.xyz[2] = z; + } + void set(int level){mData.level = level;} + void set(bool near){mData.near = near;} + + JSObjectRef makeJSObj(JSContextRef ctx){ + return JSObjectMake(ctx, getClassRef(), this); + } + +protected: + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + static bool hasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static bool setProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception); + static void getPropertyNames(JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames); + +private: + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + + sensor_type_e mType; + SensorData mData; +}; + +} // Tizen1_0 +} // TizenApis + +#endif diff --git a/src/standards/Tizen/Sensors/JSSensorDataEvent.cpp b/src/standards/Tizen/Sensors/JSSensorDataEvent.cpp new file mode 100644 index 0000000..f61ed73 --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensorDataEvent.cpp @@ -0,0 +1,338 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "JSSensorData.h" +#include "JSSensorDataEvent.h" + +#include + +#undef LOG_TAG +#define LOG_TAG "TIZEN_SENSOR" + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace TizenApis::Commons; + +namespace TizenApis { +namespace Tizen1_0 { + +static const char* DATA_ACCURACY[] = { + "unreliable", "low", "medium", "high" +}; +static const char* REASON[] = { + "read", "watch" +}; + +enum { + PROPERTY_DATA, + PROPERTY_ACCURACY, + PROPERTY_TIMESTAMP, + PROPERTY_REASON, + PROPERTY_COUNT +}; + +static const char* PROPERTY_NAMES[] = {"data", "accuracy", "timestamp", "reason"}; + +static int accuracy_map(sensor_data_accuracy_e accuracy) { + switch(accuracy){ + case SENSOR_DATA_ACCURACY_UNDEFINED: + return JSSENSOR_DATA_ACCURACY_UNDEFINED; + case SENSOR_DATA_ACCURACY_BAD: + return JSSENSOR_DATA_ACCURACY_LOW; + case SENSOR_DATA_ACCURACY_NORMAL: + return JSSENSOR_DATA_ACCURACY_MEDIUM; + case SENSOR_DATA_ACCURACY_GOOD: + case SENSOR_DATA_ACCURACY_VERYGOOD: + return JSSENSOR_DATA_ACCURACY_HIGH; + } + + return JSSENSOR_DATA_ACCURACY_UNDEFINED; +} + +JSSensorDataEvent::JSSensorDataEvent (int reason, sensor_type_e type) + : mType(type), mAccuracy(0), mTimestamp(0) +{ + setReason(reason); + mSensordata = new JSSensorData(type); + mExSensordata = NULL; +} +JSSensorDataEvent::~JSSensorDataEvent() +{ + if(mSensordata != NULL) + delete mSensordata; +} + +void JSSensorDataEvent::set (sensor_data_accuracy_e accuracy, double timestamp) +{ + if(mType == SENSOR_LIGHT || mType == SENSOR_PROXIMITY){ + mAccuracy = JSSENSOR_DATA_ACCURACY_HIGH; + } + else{ + mAccuracy = accuracy_map(accuracy); + } + mTimestamp = timestamp; +} +void JSSensorDataEvent::set (sensor_data_accuracy_e accuracy, double timestamp, float x, float y, float z) +{ + set(accuracy, timestamp); + assert(mSensordata != NULL); + mSensordata->set(x, y, z); +} +void JSSensorDataEvent::set (sensor_data_accuracy_e accuracy, double timestamp, int level) +{ + set(accuracy, timestamp); + assert(mSensordata != NULL); + mSensordata->set(level); +} +void JSSensorDataEvent::set (sensor_data_accuracy_e accuracy, double timestamp, bool near) +{ + set(accuracy, timestamp); + assert(mSensordata != NULL); + mSensordata->set(near); +} + +void JSSensorDataEvent::setReason(int reason) +{ + if(reason < JSSENSOR_REASON_READ || reason > JSSENSOR_REASON_WATCH){ + mReason = JSSENSOR_REASON_UNDEFINED; + } + else{ + mReason = reason; + } +} + +JSObjectRef JSSensorDataEvent::makeJSObj(JSContextRef ctx) +{ + return JSObjectMake(ctx, getClassRef(), this); +} + +JSClassRef JSSensorDataEvent::m_jsClassRef = NULL; + +JSClassDefinition JSSensorDataEvent::m_jsClassInfo = { + 0, + kJSClassAttributeNone, + "SensorDataEvent", + NULL, + NULL, + m_function, + initialize, + finalize, + NULL, //hasProperty, + JSSensorDataEvent::getProperty, //getProperty, + JSSensorDataEvent::setProperty, //setProperty, + NULL, //deleteProperty,Geolocation + NULL, //getPropertyNames, + NULL, + NULL, // constructor + hasInstance, + NULL +}; + +JSStaticFunction JSSensorDataEvent::m_function[] = { + { "initSensorDataEvent",JSSensorDataEvent::initSensorDataEvent,kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + + +const JSClassRef JSSensorDataEvent::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSensorDataEvent::getClassInfo() +{ + return &m_jsClassInfo; +} + + +JSObjectRef JSSensorDataEvent::m_DOMEvent = NULL; + +void JSSensorDataEvent::initialize(JSContextRef ctx, JSObjectRef object) +{ + if(m_DOMEvent == NULL){ + JSStringRef scriptJS = JSStringCreateWithUTF8CString("return Event"); + JSObjectRef fn = JSObjectMakeFunction(ctx, NULL, 0, NULL, scriptJS, NULL, 1, NULL); + JSValueRef result = JSObjectCallAsFunction(ctx, fn, NULL, 0, NULL, NULL); + JSStringRelease(scriptJS); + m_DOMEvent = JSValueToObject(ctx, result, NULL); + } + + JSStringRef jss_type = JSStringCreateWithUTF8CString("sensordata"); + JSValueRef jsv_type = JSValueMakeString(ctx, jss_type); + JSStringRelease(jss_type); + + JSValueRef args[] = {jsv_type}; + JSObjectRef domEvent = JSObjectCallAsConstructor(ctx, m_DOMEvent, 1, args, NULL); + + JSObjectSetPrototype(ctx, object, domEvent); +} + +void JSSensorDataEvent::finalize(JSObjectRef object) +{ + JSSensorDataEvent* eventData = (JSSensorDataEvent*)JSObjectGetPrivate(object); + if(eventData != NULL){ + delete eventData; + } +} + +bool JSSensorDataEvent::hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSSensorDataEvent::getProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + JSSensorDataEvent* eventData = (JSSensorDataEvent*) JSObjectGetPrivate(object); + + assert(eventData != NULL); + assert(eventData->mSensordata != NULL); + + Converter convert(ctx); + + if(JSStringIsEqualToUTF8CString(propertyName, PROPERTY_NAMES[PROPERTY_DATA])) { + if(eventData->mExSensordata != NULL) + return eventData->mExSensordata; + else + return eventData->mSensordata->makeJSObj(ctx); + } + else if(JSStringIsEqualToUTF8CString(propertyName, PROPERTY_NAMES[PROPERTY_ACCURACY])) { + if(eventData->mAccuracy != JSSENSOR_DATA_ACCURACY_UNDEFINED) + return convert.toJSValueRef(DATA_ACCURACY[eventData->mAccuracy]); + else + return JSValueMakeUndefined(ctx); + } + else if(JSStringIsEqualToUTF8CString(propertyName, PROPERTY_NAMES[PROPERTY_TIMESTAMP])) { + return convert.toJSValueRef(eventData->mTimestamp); + } + else if(JSStringIsEqualToUTF8CString(propertyName, PROPERTY_NAMES[PROPERTY_REASON])) { + if(eventData->mReason != JSSENSOR_REASON_UNDEFINED){ +// return convert.toJSValueRef(REASON[eventData->mReason]); + JSStringRef rsStr = JSStringCreateWithUTF8CString(REASON[eventData->mReason]); + JSValueRef result = JSValueMakeString(ctx, rsStr); + JSStringRelease(rsStr); + return result; + } + else + return JSValueMakeUndefined(ctx); + } + + return NULL; +} + +bool JSSensorDataEvent::setProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + for(int i=0; imSensordata != NULL); + + if(argumentCount < 7){ + // It will must be replace other error except DOMException + return JSDOMExceptionFactory::InvalidValuesException.make(ctx, exception); + } + JSValueRef jsv_type = arguments[0]; + JSValueRef jsv_bubble = arguments[1]; + JSValueRef jsv_cancelable = arguments[2]; + JSValueRef jsv_reason = arguments[3]; + JSValueRef jsv_timestamp = arguments[4]; + JSValueRef jsv_accuracy = arguments[5]; + JSValueRef jsv_data = arguments[6]; + + JSStringRef pname_type = JSStringCreateWithUTF8CString("type"); + JSObjectSetProperty(ctx, object, pname_type, jsv_type, kJSPropertyAttributeNone, NULL); + JSStringRelease(pname_type); + + JSStringRef pname_bubble = JSStringCreateWithUTF8CString("bubble"); + JSObjectSetProperty(ctx, object, pname_bubble, jsv_bubble, kJSPropertyAttributeNone, NULL); + JSStringRelease(pname_bubble); + + JSStringRef pname_cancelable = JSStringCreateWithUTF8CString("cancelable"); + JSObjectSetProperty(ctx, object, pname_cancelable, jsv_cancelable, kJSPropertyAttributeNone, NULL); + JSStringRelease(pname_cancelable); + + Converter convert(ctx); + + std::string reason = convert.toString(jsv_reason); + int r = JSSENSOR_REASON_UNDEFINED; + for(int i=0; imReason = r; + + eventData->mTimestamp = convert.toDouble(jsv_timestamp); + + std::string accuracy = convert.toString(jsv_accuracy); + int a = JSSENSOR_DATA_ACCURACY_UNDEFINED; + for(int i=0; imAccuracy = a; + + eventData->mExSensordata = jsv_data; + + return JSValueMakeUndefined(ctx); +} + +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Sensors/JSSensorDataEvent.h b/src/standards/Tizen/Sensors/JSSensorDataEvent.h new file mode 100644 index 0000000..775b314 --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensorDataEvent.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** +* @file JSSensorDataEvent.h +* @author Pius Lee (pius.lee@samsung.com) +* @version 0.1 +*/ + +#ifndef _WRTPLUGINS_TIZEN_JS_SENSOR_DATA_EVENT_ +#define _WRTPLUGINS_TIZEN_JS_SENSOR_DATA_EVENT_ + +#include +#include +#include "JSSensorData.h" + +namespace TizenApis { +namespace Tizen1_0 { + +enum { + JSSENSOR_DATA_ACCURACY_UNDEFINED = -1, + JSSENSOR_DATA_ACCURACY_UNRELIABLE, + JSSENSOR_DATA_ACCURACY_LOW, + JSSENSOR_DATA_ACCURACY_MEDIUM, + JSSENSOR_DATA_ACCURACY_HIGH, + JSSENSOR_DATA_ACCURACY_COUNT +}; + +enum { + JSSENSOR_REASON_UNDEFINED = -1, + JSSENSOR_REASON_READ, + JSSENSOR_REASON_WATCH, + JSSENSOR_REASON_COUNT +}; + +class JSSensorDataEvent { +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + JSSensorDataEvent (); + JSSensorDataEvent (int reason, sensor_type_e type); + ~JSSensorDataEvent(); + + void set (sensor_data_accuracy_e accuracy, double timestamp, float x, float y, float z); + void set (sensor_data_accuracy_e accuracy, double timestamp, int level); + void set (sensor_data_accuracy_e accuracy, double timestamp, bool near); + + void set (sensor_data_accuracy_e accuracy, double timestamp); + + void setReason(int reason); + + JSObjectRef makeJSObj(JSContextRef ctx); + +protected: + + static void initialize(JSContextRef ctx, JSObjectRef object); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + // properties get / set + static JSValueRef getProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static bool setProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception); + static bool hasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName); + static void getPropertyNames(JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames); + + static JSValueRef initSensorDataEvent(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +private: + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + static JSStaticFunction m_function[]; + static JSObjectRef m_DOMEvent; + + JSSensorData* mSensordata; + JSValueRef mExSensordata; + sensor_type_e mType; + int mAccuracy; + double mTimestamp; + int mReason; +}; + +} // Tizen1_0 +} // TizenApis + +#endif diff --git a/src/standards/Tizen/Sensors/JSSensorError.cpp b/src/standards/Tizen/Sensors/JSSensorError.cpp new file mode 100644 index 0000000..0a3d650 --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensorError.cpp @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include "JSSensorError.h" + +#include + +#undef LOG_TAG +#define LOG_TAG "TIZEN_SENSOR" + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +struct MsgCode { + string msg; + int code; +}; + +JSClassRef JSSensorError::m_jsClassRef = NULL; + +JSClassDefinition JSSensorError::m_jsClassInfo = { + 0, + kJSClassAttributeNone, + "SensorError", + NULL, + m_jsStaticProperties, + NULL, + initialize, + finalize, + NULL, //hasProperty, + JSSensorError::getProperty, //getProperty, + JSSensorError::setProperty, //setProperty, + NULL, //deleteProperty,Geolocation + NULL, //getPropertyNames, + NULL, + NULL, // constructor + hasInstance, + NULL +}; + +JSStaticValue JSSensorError::m_jsStaticProperties[] = { + {"PERMISSION_DENIED", JSSensorError::getStaticProperty, NULL, kJSPropertyAttributeReadOnly}, + {"CONNECTION_ERROR", JSSensorError::getStaticProperty, NULL, kJSPropertyAttributeReadOnly}, + {0, 0, 0, 0} +}; + + +const JSClassRef JSSensorError::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSensorError::getClassInfo() +{ + return &m_jsClassInfo; +} + +JSObjectRef JSSensorError::makeSensorError(JSContextRef ctx, const char* message, unsigned short code) +{ + struct MsgCode* msgcode = new MsgCode; + msgcode->msg = message; + msgcode->code = code; + + JSObjectRef errorObj = JSObjectMake(ctx, getClassRef(), (void*)msgcode); + + return errorObj; +} + +void JSSensorError::initialize(JSContextRef ctx, JSObjectRef object) +{ +} + +void JSSensorError::finalize(JSObjectRef object) +{ +} + +bool JSSensorError::hasInstance(JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(ctx, possibleInstance, getClassRef()); +} + +JSValueRef JSSensorError::getProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + struct MsgCode* msgcode = (struct MsgCode*) JSObjectGetPrivate(object); + if(msgcode == NULL){ + return JSValueMakeNull(ctx); + } + + if(JSStringIsEqualToUTF8CString(propertyName, "message")) { + JSStringRef msg = JSStringCreateWithUTF8CString(msgcode->msg.c_str()); + JSValueRef msgVal = JSValueMakeString(ctx, msg); + JSStringRelease(msg); + return msgVal; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "code")) { + JSValueRef msgVal = JSValueMakeNumber(ctx, msgcode->code); + return msgVal; + } + + return NULL; +} + +bool JSSensorError::setProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + // return true for read only + if(JSStringIsEqualToUTF8CString(propertyName, "message")) { + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "code")) { + return true; + } + + return false; +} + +JSValueRef JSSensorError::getStaticProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + if(JSStringIsEqualToUTF8CString(propertyName, "PERMISSION_DENIED")) { + return JSValueMakeNumber(ctx, PERMISSION_DENIED); + } + else if(JSStringIsEqualToUTF8CString(propertyName, "CONNECTION_ERROR")) { + return JSValueMakeNumber(ctx, PERMISSION_DENIED); + } + return JSValueMakeNull(ctx); +} + +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Sensors/JSSensorError.h b/src/standards/Tizen/Sensors/JSSensorError.h new file mode 100755 index 0000000..7e2b34b --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensorError.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** +* @file JSSensorError.h +* @author Pius Lee (pius.lee@samsung.com) +* @version 0.1 +*/ + +#ifndef _WRTPLUGINS_TIZEN_JS_SENSOR_ +#define _WRTPLUGINS_TIZEN_JS_SENSOR_ + +#include + +namespace TizenApis { +namespace Tizen1_0 { + +class JSSensorError { +public: + static const int PERMISSION_DENIED = -100; + static const int CONNECT_ERROR = -200; + static const int WATCH_ERROR = -300; + static const int END_WATCH_ERROR = -300; + static const int UNKNOWN_ERROR = -1000; + + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + static JSObjectRef makeSensorError(JSContextRef ctx, const char* message, unsigned short code); + +protected: + static void initialize(JSContextRef ctx, JSObjectRef object); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + // properties get / set + static JSValueRef getProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static bool setProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception); + + // get static properties function + static JSValueRef getStaticProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + +private: + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + static JSStaticValue m_jsStaticProperties[]; +}; + +} // Tizen1_0 +} // TizenApis + +#endif diff --git a/src/standards/Tizen/Sensors/JSSensorManager.cpp b/src/standards/Tizen/Sensors/JSSensorManager.cpp new file mode 100644 index 0000000..0475d04 --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensorManager.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include "JSSensorManager.h" +#include "JSSensorRequest.h" + +#include + +#undef LOG_TAG +#define LOG_TAG "TIZEN_SENSOR" + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassRef JSSensorManager::m_jsClassRef = NULL; + +JSClassDefinition JSSensorManager::m_jsClassInfo = { + 0, + kJSClassAttributeNone, + "SensorManager", + NULL, + NULL, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty,Geolocation + NULL, //getPropertyNames, + NULL, + NULL, // constructor + hasInstance, + NULL +}; + +JSStaticFunction JSSensorManager::m_function[] = { + { "findSensors",JSSensorManager::findSensors,kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef JSSensorManager::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSensorManager::getClassInfo() +{ + return &m_jsClassInfo; +} + +JSContextRef JSSensorManager::gCtx = NULL; +void JSSensorManager::initialize(JSContextRef ctx, JSObjectRef object) +{ + gCtx = ctx; +} + +void JSSensorManager::finalize(JSObjectRef object) +{ +} + +bool JSSensorManager::hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSSensorManager::findSensors(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + char type[30]; + JSObjectRef request = NULL; + if(argumentCount > 0 && JSValueIsString(ctx, arguments[0])){ + JSStringRef jss_type = JSValueToStringCopy(ctx, arguments[0], NULL); + JSStringGetUTF8CString(jss_type, type, 30); + JSStringRelease(jss_type); + request = JSSensorRequest::makeSensorRequest(ctx, type); + } + else{ + request = JSSensorRequest::makeSensorRequest(ctx, NULL); + } + + return request; +} + +} // Tizen1_0 +} // TizenApis + diff --git a/src/standards/Tizen/Sensors/JSSensorManager.h b/src/standards/Tizen/Sensors/JSSensorManager.h new file mode 100644 index 0000000..7cea249 --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensorManager.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** +* @file JSSensorManager.h +* @author Pius Lee (pius.lee@samsung.com) +* @version 0.1 +*/ + +#ifndef _WRTPLUGINS_TIZEN_JS_SENSOR_MANAGER_ +#define _WRTPLUGINS_TIZEN_JS_SENSOR_MANAGER_ + +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +enum { + JSSENSOR_TYPE_ACCELEROMETER, + JSSENSOR_TYPE_GYROSCOPE, + JSSENSOR_TYPE_ORIENTATION, + JSSENSOR_TYPE_MAGNETICFIELD, + JSSENSOR_TYPE_PROXIMITY, + JSSENSOR_TYPE_AMBIENTLIGHT, + JSSENSOR_TYPE_AMBIENTNOISE, + JSSENSOR_TYPE_TEMPERATURE, + JSSENSOR_TYPE_ATMPRESSURE, + JSSENSOR_TYPE_RELHUMIDITY, +}; + +class JSSensorManager { +public: + static JSContextRef gCtx; + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + +protected: + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + static JSValueRef findSensors(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +private: + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + static JSStaticFunction m_function[]; +}; + +} // Tizen1_0 +} // TizenApis + +#endif diff --git a/src/standards/Tizen/Sensors/JSSensorRequest.cpp b/src/standards/Tizen/Sensors/JSSensorRequest.cpp new file mode 100644 index 0000000..ffacff5 --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensorRequest.cpp @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include "JSSensorManager.h" +#include "JSSensorRequest.h" +#include "SensorType.h" + +#include + +#undef LOG_TAG +#define LOG_TAG "TIZEN_SENSOR" + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassRef JSSensorRequest::m_jsClassRef = NULL; + +JSClassDefinition JSSensorRequest::m_jsClassInfo = { + 0, + kJSClassAttributeNone, + "SensorRequest", + NULL, + NULL, + NULL, + initialize, + finalize, + NULL, //hasProperty, + JSSensorRequest::getProperty, //getProperty, + JSSensorRequest::setProperty, //setProperty, + NULL, //deleteProperty + NULL, //getPropertyNames, + NULL, + NULL, // constructor + hasInstance, + NULL +}; + +struct ResultSet { + JSObjectRef sensors; + JSObjectRef error; + JSValueRef onsuccess; + JSValueRef onerror; + char* type; + bool done; +}; + +const JSClassRef JSSensorRequest::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSensorRequest::getClassInfo() +{ + return &m_jsClassInfo; +} + +static void alert(JSContextRef ctx, JSValueRef value) +{ + JSStringRef scriptJS = JSStringCreateWithUTF8CString("return alert"); + JSObjectRef fn = JSObjectMakeFunction(ctx, NULL, 0, NULL, scriptJS, NULL, 1, NULL); + JSValueRef result = JSObjectCallAsFunction(ctx, fn, NULL, 0, NULL, NULL); + JSStringRelease(scriptJS); + JSObjectRef alertFunc = JSValueToObject(ctx, result, NULL); + + JSValueRef args[] = {value}; + JSObjectCallAsFunction(ctx, alertFunc, NULL, 1, args, NULL); +} + +static gboolean afterProcess(gpointer user_data) +{ + JSObjectRef sensorRequest = (JSObjectRef)user_data; + + struct ResultSet* result = (struct ResultSet*)JSObjectGetPrivate(sensorRequest); + const char* type = result->type; + JSContextRef ctx = JSSensorManager::gCtx; + + JSValueRef onsuccess = result->onsuccess; + JSValueRef onerror = result->onerror; + + JSObjectRef sensorArray = SensorTypeUtil::getInstance()->getSensorArray(ctx, type); + + result->sensors = sensorArray; + result->done = true; + + if(JSValueIsObject(ctx, onsuccess)){ + JSObjectRef successFunc = JSValueToObject(ctx, onsuccess, NULL); + JSObjectCallAsFunction(ctx, successFunc, sensorRequest, 0, NULL, NULL); + } + + return false; +} + +JSObjectRef JSSensorRequest::makeSensorRequest(JSContextRef ctx, const char* type) +{ + JSClassRef jsCls = getClassRef(); + + struct ResultSet* result = new ResultSet; + + JSObjectRef sensorRequest = JSObjectMake(ctx, jsCls, result); + + if(type != NULL) + result->type = strdup(type); + else + result->type = NULL; + + result->done = false; + + g_idle_add_full(G_PRIORITY_HIGH_IDLE, afterProcess, sensorRequest, NULL); + + return sensorRequest; +} + +void JSSensorRequest::initialize(JSContextRef ctx, JSObjectRef object) +{ + SensorTypeUtil::getInstance(JSSensorManager::gCtx); +} + +void JSSensorRequest::finalize(JSObjectRef object) +{ + struct ResultSet* result = (struct ResultSet*)JSObjectGetPrivate(object); + if(result != NULL){ + if(result->type != NULL){ + delete result->type; + } + delete result; + } +} + +bool JSSensorRequest::hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSSensorRequest::getProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + struct ResultSet* result = (struct ResultSet*)JSObjectGetPrivate(object); + if(result == NULL) + return NULL; + + if(JSStringIsEqualToUTF8CString(propertyName, "result")) { + if(!result->done){ + return JSDOMExceptionFactory::InvalidStateException.make(ctx, exception); + }else{ + return result->sensors; + } + } + else if(JSStringIsEqualToUTF8CString(propertyName, "error")) { + if(!result->done){ + return JSDOMExceptionFactory::InvalidStateException.make(ctx, exception); + }else{ + return result->error; + } + } + else if(JSStringIsEqualToUTF8CString(propertyName, "readyState")) { + JSStringRef state = NULL; + JSValueRef jsState = NULL; + if(!result->done){ + state = JSStringCreateWithUTF8CString("processing"); + }else{ + state = JSStringCreateWithUTF8CString("done"); + } + if(state != NULL){ + jsState = JSValueMakeString(ctx, state); + JSStringRelease(state); + } + return jsState; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "onsuccess")) { + return result->onsuccess; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "onerror")) { + return result->onerror; + } + + return NULL; +} + +bool JSSensorRequest::setProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + struct ResultSet* result = (struct ResultSet*)JSObjectGetPrivate(object); + if(JSStringIsEqualToUTF8CString(propertyName, "result")) { + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "error")) { + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "readyState")) { + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "onsuccess")) { + result->onsuccess = value; + return true; + } + else if(JSStringIsEqualToUTF8CString(propertyName, "onerror")) { + result->onerror = value; + return true; + } + + return false; +} + +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Sensors/JSSensorRequest.h b/src/standards/Tizen/Sensors/JSSensorRequest.h new file mode 100644 index 0000000..a890ba1 --- /dev/null +++ b/src/standards/Tizen/Sensors/JSSensorRequest.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** +* @file JSSensorRequest.h +* @author Pius Lee (pius.lee@samsung.com) +* @version 0.1 +*/ + +#ifndef _WRTPLUGINS_TIZEN_JS_SENSOR_REQUEST_ +#define _WRTPLUGINS_TIZEN_JS_SENSOR_REQUEST_ + +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +class JSSensorRequest { +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + static JSObjectRef makeSensorRequest(JSContextRef ctx, const char* type); + +protected: + static void initialize(JSContextRef ctx, JSObjectRef object); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + // properties + static JSValueRef getProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static bool setProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception); + +private: + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + + JSObjectRef onsuccess; + JSObjectRef onerror; +}; + +} // Tizen1_0 +} // TizenApis + +#endif diff --git a/src/standards/Tizen/Sensors/SensorType.cpp b/src/standards/Tizen/Sensors/SensorType.cpp new file mode 100644 index 0000000..fdeb3f6 --- /dev/null +++ b/src/standards/Tizen/Sensors/SensorType.cpp @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "SensorType.h" +#include +#include "JSSensor.h" + +using namespace std; + +namespace TizenApis { +namespace Tizen1_0 { + +int SensorTypeUtil::modifyType(const char* type) +{ + if(strcmp(type, ACC_TYPE) == 0){ + return SENSOR_ACCELEROMETER; + } + else if(strcmp(type, MAG_TYPE) == 0){ + return SENSOR_MAGNETIC; + } + else if(strcmp(type, ORI_TYPE) == 0){ + return SENSOR_ORIENTATION; + } + else if(strcmp(type, GYR_TYPE) == 0){ + return SENSOR_GYROSCOPE; + } + else if(strcmp(type, LIG_TYPE) == 0){ + return SENSOR_LIGHT; + } + else if(strcmp(type, PRX_TYPE) == 0){ + return SENSOR_PROXIMITY; + } + + return -1; +} +int SensorTypeUtil::modifyType(const char* type, const char* name) +{ + if(strcmp(type, ACC_TYPE) == 0 && strcmp(name, ACC_NAME) == 0){ + return SENSOR_ACCELEROMETER; + } + else if(strcmp(type, MAG_TYPE) == 0 && strcmp(name, MAG_NAME) == 0){ + return SENSOR_MAGNETIC; + } + else if(strcmp(type, ORI_TYPE) == 0 && strcmp(name, ORI_NAME) == 0){ + return SENSOR_ORIENTATION; + } + else if(strcmp(type, GYR_TYPE) == 0 && strcmp(name, GYR_NAME) == 0){ + return SENSOR_GYROSCOPE; + } + else if(strcmp(type, LIG_TYPE) == 0 && strcmp(name, LIG_NAME) == 0){ + return SENSOR_LIGHT; + } + else if(strcmp(type, PRX_TYPE) == 0 && strcmp(name, PRX_NAME) == 0){ + return SENSOR_PROXIMITY; + } + + return -1; +} + +static const char* JSS_TYPE[] = { + ACC_TYPE, MAG_TYPE, ORI_TYPE, GYR_TYPE, LIG_TYPE, PRX_TYPE +}; + +static const char* JSS_NAME[] = { + ACC_NAME, MAG_NAME, ORI_NAME, GYR_NAME, LIG_NAME, PRX_NAME +}; + +void SensorTypeUtil::modifyType(sensor_type_e type, char* jstypeBuf, int buflen) +{ + if(jstypeBuf == NULL || type < SENSOR_ACCELEROMETER || type > SENSOR_PROXIMITY) return; + strncpy(jstypeBuf, JSS_TYPE[type], buflen); +} +void SensorTypeUtil::modifyName(sensor_type_e type, char* jsnameBuf, int buflen) +{ + if(jsnameBuf == NULL || type < SENSOR_ACCELEROMETER || type > SENSOR_PROXIMITY) return; + strncpy(jsnameBuf, JSS_TYPE[type], buflen); +} + + +SensorTypeUtil* SensorTypeUtil::instance = NULL; +SensorTypeUtil* SensorTypeUtil::getInstance(JSContextRef ctx) +{ + if(instance == NULL){ + instance = new SensorTypeUtil(ctx); + } + instance->m_ctx = ctx; + return instance; +} +SensorTypeUtil* SensorTypeUtil::getInstance() +{ + if(instance == NULL){ + return NULL; + } + return instance; +} + +int MinDelay[] = { + 20,// SENSOR_ACCELEROMETER + 20,// SENSOR_MAGNETIC + 20,// SENSOR_ORIENTATION + 20,// SENSOR_GYROSCOPE + 100,// SENSOR_LIGHT + 0,// SENSOR_PROXIMITY +}; + +JSObjectRef SensorTypeUtil::makeSensor(JSContextRef ctx, sensor_type_e type) +{ + float max, min, res; + char buf[30]; + if(type < SENSOR_ACCELEROMETER || type > SENSOR_PROXIMITY){ + return NULL; + } + sensor_get_spec(type, &max, &min, &res); + + JSSensor* so = new JSSensor(); + so->typeId = type; + JSObjectRef sensor = JSObjectMake(ctx, JSSensor::getClassRef(), so); + JSStringRef pname_resolution = JSStringCreateWithUTF8CString("resolution"); + JSStringRef pname_minDelay = JSStringCreateWithUTF8CString("minDelay"); + JSStringRef pname_range = JSStringCreateWithUTF8CString("range"); + JSStringRef pname_name = JSStringCreateWithUTF8CString("name"); + JSStringRef pname_type = JSStringCreateWithUTF8CString("type"); + + JSObjectSetProperty(ctx, sensor, pname_resolution, + JSValueMakeNumber(ctx, res), kJSPropertyAttributeReadOnly, NULL); + JSObjectSetProperty(ctx, sensor, pname_minDelay, + JSValueMakeNumber(ctx, MinDelay[type]), kJSPropertyAttributeReadOnly, NULL); + JSObjectSetProperty(ctx, sensor, pname_range, + JSValueMakeNumber(ctx, max), kJSPropertyAttributeReadOnly, NULL); + + modifyName(type, buf, 30); + so->name = buf; + JSStringRef name_val = JSStringCreateWithUTF8CString(buf); + JSObjectSetProperty(ctx, sensor, pname_name, + JSValueMakeString(ctx, name_val), kJSPropertyAttributeReadOnly, NULL); + JSStringRelease(name_val); + + modifyType(type, buf, 30); + so->name = buf; + JSStringRef type_val = JSStringCreateWithUTF8CString(buf); + JSObjectSetProperty(ctx, sensor, pname_type, + JSValueMakeString(ctx, type_val), kJSPropertyAttributeReadOnly, NULL); + JSStringRelease(type_val); + + JSStringRelease(pname_resolution); + JSStringRelease(pname_minDelay); + JSStringRelease(pname_range); + JSStringRelease(pname_name); + JSStringRelease(pname_type); + + return sensor; +} + +static const sensor_type_e availables[] = { + SENSOR_ACCELEROMETER, + SENSOR_MAGNETIC, + SENSOR_ORIENTATION, + SENSOR_GYROSCOPE, + SENSOR_LIGHT, + SENSOR_PROXIMITY +}; +static const int availables_size = 6; + +SensorTypeUtil::SensorTypeUtil(JSContextRef ctx) +{ + m_ctx = ctx; +} + +JSObjectRef SensorTypeUtil::getSensor(JSContextRef ctx, sensor_type_e stype) +{ + JSObjectRef obj = makeSensor(m_ctx, stype); + if(obj != NULL){ + return obj; + } + + return NULL; +} + +JSObjectRef SensorTypeUtil::getSensorArray(JSContextRef ctx, const char* type) +{ + JSValueRef* ss = NULL; + int scount = 0; + if(type == NULL){ + vector all_sensors; + for(int i=0; i 0) + obj = makeSensor(m_ctx, (sensor_type_e)t); + if(obj != NULL){ + ss = new JSValueRef[1]; + ss[0] = obj; + scount = 1; + } + } + + JSObjectRef sensorArray = JSObjectMakeArray(ctx, scount, ss, NULL); + if(ss != NULL) + delete ss; + + return sensorArray; +} + +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Sensors/SensorType.h b/src/standards/Tizen/Sensors/SensorType.h new file mode 100644 index 0000000..99e86c8 --- /dev/null +++ b/src/standards/Tizen/Sensors/SensorType.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** +* @file SensorType.h +* @author Pius Lee (pius.lee@samsung.com) +* @version 0.1 +*/ + +#ifndef _WRTPLUGINS_TIZEN_SENSORTYPE_ +#define _WRTPLUGINS_TIZEN_SENSORTYPE_ + +#include +#include +#include +#include + +#define TIZEN_SENSOR_PREFIX "Tizen" + +#define ACC_TYPE "Accelerometer" +#define MAG_TYPE "MagneticField" +#define ORI_TYPE "Orientation" +#define GYR_TYPE "Gyroscope" +#define LIG_TYPE "AmbientLight" +#define PRX_TYPE "Proximity" + +#define ACC_NAME TIZEN_SENSOR_PREFIX ACC_TYPE +#define MAG_NAME TIZEN_SENSOR_PREFIX MAG_TYPE +#define ORI_NAME TIZEN_SENSOR_PREFIX ORI_TYPE +#define GYR_NAME TIZEN_SENSOR_PREFIX GYR_TYPE +#define LIG_NAME TIZEN_SENSOR_PREFIX LIG_TYPE +#define PRX_NAME TIZEN_SENSOR_PREFIX PRX_TYPE + +namespace TizenApis { +namespace Tizen1_0 { + +class SensorTypeUtil +{ + public: + static int modifyType(const char* jstype); + static int modifyType(const char* jstype, const char* name); + static void modifyType(sensor_type_e type, char* jstype, int buflen); + static void modifyName(sensor_type_e type, char* jsname, int buflen); + static JSObjectRef makeSensor(JSContextRef ctx, sensor_type_e type); + + static SensorTypeUtil* getInstance(JSContextRef ctx); + static SensorTypeUtil* getInstance(); + + JSObjectRef getSensorArray(JSContextRef ctx, const char* type); + JSObjectRef getSensor(JSContextRef ctx, sensor_type_e stype); + + private: + static SensorTypeUtil* instance; + SensorTypeUtil(JSContextRef ctx); + JSContextRef m_ctx; + std::vector sensors; +}; + +} // Tizen1_0 +} // TizenApis + + +#endif diff --git a/src/standards/Tizen/Sensors/config.xml b/src/standards/Tizen/Sensors/config.xml new file mode 100644 index 0000000..042592e --- /dev/null +++ b/src/standards/Tizen/Sensors/config.xml @@ -0,0 +1,18 @@ + + + + libwrt-plugins-tizen-1.0-sensors.so + sensors.install.uri + SAMSUNG plugin group + SAMSUNG certificate authority + AAAABBBBCCCCDDDEEEE0000 + + + http://tizen.org/api/sensors + sensors + + + + + + diff --git a/src/standards/Tizen/Sensors/plugin_initializer.cpp b/src/standards/Tizen/Sensors/plugin_initializer.cpp new file mode 100644 index 0000000..08af0d9 --- /dev/null +++ b/src/standards/Tizen/Sensors/plugin_initializer.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** +* @file Plugin_initializer.cpp +* @author Pius Lee (pius.lee@samsung.com) +* @version 0.1 +*/ + +#include +#include +#include +#include +#include "JSSensorManager.h" +#include "JSSensorConnection.h" + +void on_widget_start_callback(int widgetId, JavaScriptContext context, const engine_interface_t *interface) { + LogDebug("[Tizen\\Sensors ] on_widget_start_callback ("< +#include +#include "JSCellularNetworkInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace Api::Systeminfo; + +namespace { +const char* CELLULARNETWORK_STATUS_PROPERTY = "status"; +const char* CELLULARNETWORK_APN_PROPERTY = "apn"; +const char* CELLULARNETWORK_IPADDRESS_PROPERTY = "ipAddress"; +const char* CELLULARNETWORK_MCC_PROPERTY = "mcc"; +const char* CELLULARNETWORK_MNC_PROPERTY = "mnc"; +const char* CELLULARNETWORK_CELLID_PROPERTY = "cellid"; +const char* CELLULARNETWORK_LAC_PROPERTY = "lac"; +const char* CELLULARNETWORK_SERVICETYPE_PROPERTY = "serviceType"; +const char* CELLULARNETWORK_ROAMING_PROPERTY = "isRoaming"; +} + +JSClassRef JSCellularNetworkInfo::m_classRef = NULL; + +JSClassDefinition JSCellularNetworkInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "cellularnetworkinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSCellularNetworkInfo::m_properties[] = { + { CELLULARNETWORK_STATUS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_APN_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_IPADDRESS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_MCC_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_MNC_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_CELLID_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_LAC_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_SERVICETYPE_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_ROAMING_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSCellularNetworkInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSCellularNetworkInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSCellularNetworkInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSCellularNetworkInfo::Finalize(JSObjectRef object) +{ + LogDebug("Entered"); + JSCellularNetworkPriv* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting CellularNetworkInfo object"); + delete priv; +} + +bool JSCellularNetworkInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSCellularNetworkInfo::createJSObject(JSContextRef context, const Api::Systeminfo::CellularNetworkProperties &cellularNetworkInfo) +{ + LogDebug("Enter"); + std::auto_ptr accProps(new Api::Systeminfo::CellularNetworkProperties(cellularNetworkInfo)); + JSCellularNetworkPriv *priv = new JSCellularNetworkPriv(context, accProps.get()); + accProps.release(); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSCellularNetworkInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("Enter"); + JSCellularNetworkPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (NULL == priv) { + LogError("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + Api::Systeminfo::CellularNetworkProperties *cellularNetworkInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_STATUS_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->status); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_APN_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->apn); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_IPADDRESS_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->ipAddress); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_MCC_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->mcc); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_MNC_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->mnc); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_CELLID_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->cellid); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_LAC_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->lac); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_SERVICETYPE_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->serviceType); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_ROAMING_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->isRoaming); + } + } + Catch(Exception) + { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/src/standards/Tizen/Systeminfo/JSCellularNetworkInfo.h b/src/standards/Tizen/Systeminfo/JSCellularNetworkInfo.h new file mode 100755 index 0000000..532169d --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSCellularNetworkInfo.h @@ -0,0 +1,49 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_TIZEN1_0_CELLULARNETWORK_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_CELLULARNETWORK_INFO_H_ + +#include +#include "API/Systeminfo/SysteminfoPropertyInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSCellularNetworkPriv; + +class JSCellularNetworkInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const Api::Systeminfo::CellularNetworkProperties &cellularNetworkInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/src/standards/Tizen/Systeminfo/JSCpuInfo.cpp b/src/standards/Tizen/Systeminfo/JSCpuInfo.cpp new file mode 100755 index 0000000..9a9a92f --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSCpuInfo.cpp @@ -0,0 +1,125 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include "JSCpuInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace Api::Systeminfo; + +namespace { +const char* CPU_LOAD_PROPERTY = "load"; +} + +JSClassRef JSCpuInfo::m_classRef = NULL; + +JSClassDefinition JSCpuInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "cpuinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSCpuInfo::m_properties[] = { + { CPU_LOAD_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSCpuInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSCpuInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSCpuInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSCpuInfo::Finalize(JSObjectRef object) +{ + LogDebug("Entered"); + JSCpuPriv* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting CpuInfo object"); + delete priv; +} + +bool JSCpuInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSCpuInfo::createJSObject(JSContextRef context, const Api::Systeminfo::CpuProperties &cpuInfo) +{ + LogDebug("Enter"); + std::auto_ptr accProps(new Api::Systeminfo::CpuProperties(cpuInfo)); + JSCpuPriv *priv = new JSCpuPriv(context, accProps.get()); + accProps.release(); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSCpuInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("Enter"); + JSCpuPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (NULL == priv) { + LogError("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + Api::Systeminfo::CpuProperties *cpuInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, CPU_LOAD_PROPERTY)) { + return convert.toJSValueRef(cpuInfo->load); + } + } + Catch(Exception) + { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/src/standards/Tizen/Systeminfo/JSCpuInfo.h b/src/standards/Tizen/Systeminfo/JSCpuInfo.h new file mode 100755 index 0000000..cb3d9b9 --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSCpuInfo.h @@ -0,0 +1,49 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_TIZEN1_0_CPU_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_CPU_INFO_H_ + +#include +#include "API/Systeminfo/SysteminfoPropertyInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSCpuPriv; + +class JSCpuInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const Api::Systeminfo::CpuProperties &cpuInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/src/standards/Tizen/Systeminfo/JSDeviceInfo.cpp b/src/standards/Tizen/Systeminfo/JSDeviceInfo.cpp new file mode 100755 index 0000000..508ad5c --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSDeviceInfo.cpp @@ -0,0 +1,137 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include "JSDeviceInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace Api::Systeminfo; + +namespace { +const char* DEVICE_IMEI_PROPERTY = "imei"; +const char* DEVICE_MODEL_PROPERTY = "model"; +const char* DEVICE_VERSION_PROPERTY = "version"; +const char* DEVICE_VENDOR_PROPERTY = "vendor"; +} + +JSClassRef JSDeviceInfo::m_classRef = NULL; + +JSClassDefinition JSDeviceInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "deviceinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSDeviceInfo::m_properties[] = { + { DEVICE_IMEI_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_MODEL_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_VERSION_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_VENDOR_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSDeviceInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSDeviceInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSDeviceInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSDeviceInfo::Finalize(JSObjectRef object) +{ + LogDebug("Entered"); + JSDevicePriv* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting DeviceInfo object"); + delete priv; +} + +bool JSDeviceInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSDeviceInfo::createJSObject(JSContextRef context, const Api::Systeminfo::DeviceProperties &deviceInfo) +{ + LogDebug("Enter"); + std::auto_ptr accProps(new Api::Systeminfo::DeviceProperties(deviceInfo)); + JSDevicePriv *priv = new JSDevicePriv(context, accProps.get()); + accProps.release(); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSDeviceInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("Enter"); + JSDevicePriv *priv = static_cast(JSObjectGetPrivate(object)); + if (NULL == priv) { + LogError("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + Api::Systeminfo::DeviceProperties *deviceInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_IMEI_PROPERTY)) { + return convert.toJSValueRef(deviceInfo->imei); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_MODEL_PROPERTY)) { + return convert.toJSValueRef(deviceInfo->model); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_VERSION_PROPERTY)) { + return convert.toJSValueRef(deviceInfo->version); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_VENDOR_PROPERTY)) { + return convert.toJSValueRef(deviceInfo->vendor); + } + } + Catch(Exception) + { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/src/standards/Tizen/Systeminfo/JSDeviceInfo.h b/src/standards/Tizen/Systeminfo/JSDeviceInfo.h new file mode 100755 index 0000000..86e409c --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSDeviceInfo.h @@ -0,0 +1,49 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_TIZEN1_0_DEVICE_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_DEVICE_INFO_H_ + +#include +#include "API/Systeminfo/SysteminfoPropertyInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSDevicePriv; + +class JSDeviceInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const Api::Systeminfo::DeviceProperties &deviceInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/src/standards/Tizen/Systeminfo/JSDisplayInfo.cpp b/src/standards/Tizen/Systeminfo/JSDisplayInfo.cpp new file mode 100755 index 0000000..4b73136 --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSDisplayInfo.cpp @@ -0,0 +1,147 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include "JSDisplayInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace Api::Systeminfo; + +namespace { +const char* DISPLAY_RESOLUTIONW_PROPERTY = "resolutionWidth"; +const char* DISPLAY_RESOLUTIONH_PROPERTY = "resolutionHeight"; +const char* DISPLAY_INCHW_PROPERTY = "dotsPerInchWidth"; +const char* DISPLAY_INCHH_PROPERTY = "dotsPerInchHeight"; +const char* DISPLAY_PHYSICALW_PROPERTY = "physicalWidth"; +const char* DISPLAY_PHYSICALH_PROPERTY = "physicalHeight"; +const char* DISPLAY_BRIGHTNESS_PROPERTY = "brightness"; +} + +JSClassRef JSDisplayInfo::m_classRef = NULL; + +JSClassDefinition JSDisplayInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "displayinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSDisplayInfo::m_properties[] = { + { DISPLAY_RESOLUTIONW_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DISPLAY_RESOLUTIONH_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DISPLAY_INCHW_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DISPLAY_INCHH_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DISPLAY_PHYSICALW_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DISPLAY_PHYSICALH_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DISPLAY_BRIGHTNESS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSDisplayInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSDisplayInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSDisplayInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSDisplayInfo::Finalize(JSObjectRef object) +{ + LogDebug("Entered"); + JSDisplayPriv* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting DisplayInfo object"); + delete priv; +} + +bool JSDisplayInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSDisplayInfo::createJSObject(JSContextRef context, const Api::Systeminfo::DisplayProperties &displayInfo) +{ + std::auto_ptr accProps(new Api::Systeminfo::DisplayProperties(displayInfo)); + JSDisplayPriv *priv = new JSDisplayPriv(context, accProps.get()); + accProps.release(); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSDisplayInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("Enter"); + JSDisplayPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (NULL == priv) { + LogError("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + Api::Systeminfo::DisplayProperties *displayInfo = priv->getObject(); + Converter convert(context); + if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_RESOLUTIONW_PROPERTY)) { + return convert.toJSValueRef(displayInfo->resolutionWidth); + } else if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_RESOLUTIONH_PROPERTY)) { + return convert.toJSValueRef(displayInfo->resolutionHeight); + } else if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_INCHW_PROPERTY)) { + return convert.toJSValueRef(displayInfo->dotsPerInchWidth); + } else if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_INCHH_PROPERTY)) { + return convert.toJSValueRef(displayInfo->dotsPerInchHeight); + } else if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_PHYSICALW_PROPERTY)) { + return convert.toJSValueRef(displayInfo->physicalWidth); + } else if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_PHYSICALH_PROPERTY)) { + return convert.toJSValueRef(displayInfo->physicalHeight); + } else if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_BRIGHTNESS_PROPERTY)) { + return convert.toJSValueRef(displayInfo->brightness); + } + } + Catch(Exception) + { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/src/standards/Tizen/Systeminfo/JSDisplayInfo.h b/src/standards/Tizen/Systeminfo/JSDisplayInfo.h new file mode 100755 index 0000000..726f6e9 --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSDisplayInfo.h @@ -0,0 +1,49 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_TIZEN1_0_DISPLAY_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_DISPLAY_INFO_H_ + +#include +#include "API/Systeminfo/SysteminfoPropertyInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSDisplayPriv; + +class JSDisplayInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const Api::Systeminfo::DisplayProperties &displayInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/src/standards/Tizen/Systeminfo/JSPowerInfo.cpp b/src/standards/Tizen/Systeminfo/JSPowerInfo.cpp new file mode 100755 index 0000000..419db88 --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSPowerInfo.cpp @@ -0,0 +1,128 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include "JSPowerInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace Api::Systeminfo; + +namespace { +const char* POWER_LEVEL_PROPERTY = "level"; +const char* POWER_ISCHARGING_PROPERTY = "isCharging"; +} + +JSClassRef JSPowerInfo::m_classRef = NULL; + +JSClassDefinition JSPowerInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "powerinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSPowerInfo::m_properties[] = { + { POWER_LEVEL_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { POWER_ISCHARGING_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSPowerInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSPowerInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSPowerInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSPowerInfo::Finalize(JSObjectRef object) +{ + LogDebug("Entered"); + JSPowerPriv* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting powerInfo object"); + delete priv; +} + +bool JSPowerInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSPowerInfo::createJSObject(JSContextRef context, const Api::Systeminfo::PowerProperties &powerInfo) +{ + std::auto_ptr accProps(new Api::Systeminfo::PowerProperties(powerInfo)); + JSPowerPriv *priv = new JSPowerPriv(context, accProps.get()); + accProps.release(); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSPowerInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("Enter"); + JSPowerPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (NULL == priv) { + LogError("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + Api::Systeminfo::PowerProperties *powerInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, POWER_LEVEL_PROPERTY)) { + return convert.toJSValueRef(powerInfo->level); + } else if (JSStringIsEqualToUTF8CString(propertyName, POWER_ISCHARGING_PROPERTY)) { + return convert.toJSValueRef(powerInfo->isCharging); + } + } + Catch(Exception) + { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/src/standards/Tizen/Systeminfo/JSPowerInfo.h b/src/standards/Tizen/Systeminfo/JSPowerInfo.h new file mode 100755 index 0000000..fe7e68a --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSPowerInfo.h @@ -0,0 +1,49 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_TIZEN1_0_POWER_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_POWER_INFO_H_ + +#include +#include "API/Systeminfo/SysteminfoPropertyInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSPowerPriv; + +class JSPowerInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const Api::Systeminfo::PowerProperties &powerInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/src/standards/Tizen/Systeminfo/JSStorageInfo.cpp b/src/standards/Tizen/Systeminfo/JSStorageInfo.cpp new file mode 100755 index 0000000..5d51f80 --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSStorageInfo.cpp @@ -0,0 +1,135 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include "JSStorageInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace Api::Systeminfo; + +namespace { +const char* STORAGE_TYPE_PROPERTY = "type"; +const char* STORAGE_CAPACITY_PROPERTY = "capacity"; +const char* STORAGE_AVAILCAPA_PROPERTY = "availableCapacity"; +const char* STORAGE_REMOVEABLE_PROPERTY = "isRemoveable"; +} + +JSClassRef JSStorageInfo::m_classRef = NULL; + +JSClassDefinition JSStorageInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "storageinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSStorageInfo::m_properties[] = { + { STORAGE_TYPE_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STORAGE_CAPACITY_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STORAGE_AVAILCAPA_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STORAGE_REMOVEABLE_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSStorageInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSStorageInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSStorageInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSStorageInfo::Finalize(JSObjectRef object) +{ + LogDebug("Entered"); + JSStoragePriv* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting StorageInfo object"); + delete priv; +} + +bool JSStorageInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSStorageInfo::createJSObject(JSContextRef context, const Api::Systeminfo::StorageProperties &storageInfo) +{ + std::auto_ptr accProps(new Api::Systeminfo::StorageProperties(storageInfo)); + JSStoragePriv *priv = new JSStoragePriv(context, accProps.get()); + accProps.release(); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSStorageInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("Enter"); + JSStoragePriv *priv = static_cast(JSObjectGetPrivate(object)); + if (NULL == priv) { + LogError("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + Api::Systeminfo::StorageProperties *storageInfo = priv->getObject(); + Converter convert(context); + if (JSStringIsEqualToUTF8CString(propertyName, STORAGE_TYPE_PROPERTY)) { + return convert.toJSValueRef(storageInfo->type); + } else if (JSStringIsEqualToUTF8CString(propertyName, STORAGE_CAPACITY_PROPERTY)) { + return convert.toJSValueRef(storageInfo->capacity); + } else if (JSStringIsEqualToUTF8CString(propertyName, STORAGE_AVAILCAPA_PROPERTY)) { + return convert.toJSValueRef(storageInfo->availableCapacity); + } else if (JSStringIsEqualToUTF8CString(propertyName, STORAGE_REMOVEABLE_PROPERTY)) { + return convert.toJSValueRef(storageInfo->isRemoveable); + } + } + Catch(Exception) + { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/src/standards/Tizen/Systeminfo/JSStorageInfo.h b/src/standards/Tizen/Systeminfo/JSStorageInfo.h new file mode 100755 index 0000000..30a6d7c --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSStorageInfo.h @@ -0,0 +1,49 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_TIZEN1_0_STORAGE_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_STORAGE_INFO_H_ + +#include +#include "API/Systeminfo/SysteminfoPropertyInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSStoragePriv; + +class JSStorageInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const Api::Systeminfo::StorageProperties &storageInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/src/standards/Tizen/Systeminfo/JSSysteminfo.cpp b/src/standards/Tizen/Systeminfo/JSSysteminfo.cpp new file mode 100755 index 0000000..b5a6ddb --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSSysteminfo.cpp @@ -0,0 +1,380 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "JSSysteminfo.h" +#include "plugin_config.h" + +namespace TizenApis { +namespace Tizen1_0 { + +using namespace std; +using namespace DPL; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace Api::Systeminfo; +using namespace TizenApis::Commons; + +JSClassDefinition JSSysteminfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "systeminfo", + NULL, + NULL, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticFunction JSSysteminfo::m_function[] = { + { "isSupported", JSSysteminfo::isSupported, kJSPropertyAttributeNone }, + { "getPropertyValue", JSSysteminfo::getPropertyValue, kJSPropertyAttributeNone }, + { "addPropertyValueChangedListener", JSSysteminfo::addPropertyValueChangedListener, kJSPropertyAttributeNone }, + { "removePropertyChangedListener", JSSysteminfo::removePropertyChangedListener, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef JSSysteminfo::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSysteminfo::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSSysteminfo::m_jsClassRef = JSClassCreate(JSSysteminfo::getClassInfo()); + +void JSSysteminfo::initialize(JSContextRef context, JSObjectRef object) +{ + JSSysteminfoPriv* priv = static_cast(JSObjectGetPrivate(object)); + assert(!priv && "Invalid object creation."); + ISysteminfoPtr Systeminfos(SysteminfoFactory::getInstance().getSysteminfos()); + priv = new JSSysteminfoPriv(context, Systeminfos); + if (!JSObjectSetPrivate(object, static_cast(priv))) { + LogError("Object can't store private data."); + delete priv; + } + + LogDebug("JSSysteminfo::initialize "); +} + +void JSSysteminfo::finalize(JSObjectRef object) +{ + JSSysteminfoPriv* priv = static_cast(JSObjectGetPrivate(object)); + + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting gallery"); + delete priv; +} + +JSValueRef JSSysteminfo::isSupported(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + JSSysteminfoPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(priv->getContext(),SYSTEMINFO_FUNCTION_API_IS_SUPPORTED); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Converter converter(context); + Validator check(context, exception); + + if (argumentCount < 1) { + LogError("wrong argument"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + } + if (argumentCount > 0 && JSValueIsObject(context, arguments[0])) { + LogError("wrong argument"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + + Try + { + ISysteminfoPtr Systeminfos(priv->getObject()); + + bool retVal; + retVal = Systeminfos->isPropertyValid(priv->getContext(), arguments[0]); + + return converter.toJSValueRef(retVal); + } + + Catch(ConversionException) { + LogError("Error on conversion"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSSysteminfo::getPropertyValue(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + JSSysteminfoPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(priv->getContext(),SYSTEMINFO_FUNCTION_API_GET_PROPERTY_VALUE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Converter converter(context); + Validator check(context, exception); + + if (!priv) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "unknown error"); + } + + if (argumentCount == 0 || argumentCount > 4) { + LogError("wrong argument"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + } + + if (!JSValueIsNull(context, arguments[1]) && !JSValueIsUndefined(context, arguments[1]) && !check.isCallback(arguments[1])) { + LogError("wrong argument"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + + if (argumentCount > 2) { + if (!JSValueIsNull(context, arguments[2]) && !JSValueIsUndefined(context, arguments[2]) && !check.isCallback(arguments[2])) { + LogError("wrong argument"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (check.isCallback(arguments[1])) { + onSuccessForCbm = arguments[1]; + } + if (argumentCount > 2) { + if (check.isCallback(arguments[2])) { + onErrorForCbm = arguments[2]; + } + } + + JSCallbackManagerPtr cbm(JSCallbackManager::createObject(priv->getContext(), onSuccessForCbm, onErrorForCbm, true, true)); + + cbm->setObject(thisObject); + + Try { + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) + || JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1])) { + LogError("successCallback parameter is JSNull/JSUndefined"); + Throw(InvalidArgumentException); + } + + ISysteminfoPtr Systeminfos(priv->getObject()); + + EventGetSysteminfoPtr event(new EventGetSysteminfo()); + + event->setBasePropertyPtr(Systeminfos->getBasePropertyPtr(priv->getContext(), arguments[0])); + event->setPrivateData(StaticPointerCast(cbm)); + + SysteminfoListener& listener = SysteminfoListener::getInstance(); + event->setForAsynchronousCall(&listener); + + JSObjectRef pendingOperation = makePendingOperation(context, event); + Systeminfos->get(event); + + return pendingOperation; + } + + Catch(PendingOperationException) { + LogError("JSSysteminfo::get PendingOperationException"); + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"invalid parameter")); + } + Catch(ConversionException) { + LogError("JSSysteminfo::get ConversionException"); + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"invalid parameter")); + } + Catch(InvalidArgumentException) { + LogError("JSSysteminfo::get InvalidArgumentException"); + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"invalid parameter")); + } + Catch(WrtDeviceApis::Commons::Exception) { + LogError("JSSysteminfo::get Exception"); + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"invalid parameter")); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSSysteminfo::addPropertyValueChangedListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + LogDebug("enter"); + JSValueRef property = NULL; + WatchOption option; + int failId = -1; + JSSysteminfoPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(priv->getContext(),SYSTEMINFO_FUNCTION_API_ADD_PROPERTY_VALUE_CHANGED_LISTENER); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Converter converter(context); + Validator check(context, exception); + + if (!priv) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "unknown error"); + } + + if (argumentCount == 0 || argumentCount > 4) { + LogError("wrong argument"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "type mismatch error"); + } + + if (!JSValueIsNull(context, arguments[1]) && !JSValueIsUndefined(context, arguments[1]) && !check.isCallback(arguments[1])) { + LogError("wrong argument"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + + if (argumentCount > 2) { + if (!JSValueIsNull(context, arguments[2]) && !JSValueIsUndefined(context, arguments[2]) && !check.isCallback(arguments[2])) { + LogError("wrong argument"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + if (check.isCallback(arguments[1])) { + onSuccessForCbm = arguments[1]; + } + if (argumentCount > 2) { + if (check.isCallback(arguments[2])) { + onErrorForCbm = arguments[2]; + } + } + JSCallbackManagerPtr cbm(JSCallbackManager::createObject(priv->getContext(), onSuccessForCbm, onErrorForCbm, true, true)); + cbm->setObject(thisObject); + + Try { + if (JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0]) + || JSValueIsNull(context, arguments[1]) || JSValueIsUndefined(context, arguments[1])) { + LogError("successCallback parameter is JSNull/JSUndefined"); + Throw(InvalidArgumentException); + } + property = arguments[0]; + if (argumentCount > 3 && JSValueIsObject(context, arguments[3])) { + option.timeout = converter.toULong(JSUtils::getJSProperty(context, arguments[3], "timeout", exception)); + option.highThreshold = converter.toDouble(JSUtils::getJSProperty(context, arguments[3], "highThreshold", exception)); + option.lowThreshold = converter.toDouble(JSUtils::getJSProperty(context, arguments[3], "lowThreshold", exception)); + } + ISysteminfoPtr Systeminfos(priv->getObject()); + + if(Systeminfos->isDuplicateWatch((const char *)converter.toString(property).c_str())) { + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"invalid parameter")); + return converter.toJSValueRef(failId); + } else { + EventWatchSysteminfoPtr event(new EventWatchSysteminfo); + event->setWatchOption(option); + event->setBasePropertyPtr(Systeminfos->getBasePropertyPtr(priv->getContext(), property)); + event->setPrivateData(StaticPointerCast(cbm)); + + SysteminfoListener& listener = SysteminfoListener::getInstance(); + event->setForAsynchronousCall(&listener); + + Systeminfos->watch(event); + return converter.toJSValueRef(event->getId()); + } + } + + Catch(PendingOperationException) { + LogError("JSSysteminfo::get PendingOperationException"); + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"invalid parameter")); + } + Catch(ConversionException) { + LogError("JSSysteminfo::get ConversionException"); + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"invalid parameter")); + } + Catch(InvalidArgumentException) { + LogError("JSSysteminfo::get InvalidArgumentException"); + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"invalid parameter")); + } + Catch(WrtDeviceApis::Commons::Exception) { + LogError("JSSysteminfo::get Exception"); + cbm->callOnError(JSTizenExceptionFactory::makeErrorObject(context, JSTizenException::INVALID_VALUES_ERROR,"invalid parameter")); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSSysteminfo::removePropertyChangedListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + int id = 0; + JSSysteminfoPriv *priv = static_cast(JSObjectGetPrivate(thisObject)); + + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(priv->getContext(),SYSTEMINFO_FUNCTION_API_REMOVE_PROPERTY_CHANGED_LISTENER); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Converter converter(context); + + if (argumentCount == 0) { + return JSValueMakeUndefined(context); + } else if (argumentCount != 1 || (argumentCount > 0 && JSValueIsObject(context, arguments[0]))) { + LogError("wrong argument"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "invalid value error"); + } + + Try { + if (!priv) { + ThrowMsg(NullPointerException, "No private object"); + } + ISysteminfoPtr Systeminfos(priv->getObject()); + + if (argumentCount == 1) { + id = static_cast(converter.toInt(arguments[0])); + } + LogDebug("clearWatch id = " << id ); + Systeminfos->clearWatch(id); + return JSValueMakeUndefined(context); + } + Catch (InvalidArgumentException) { + LogError("JSSysteminfo::get InvalidArgumentException"); + } + Catch (WrtDeviceApis::Commons::Exception) { + LogError("JSSysteminfo::get Exception"); + } + + return JSValueMakeUndefined(context); +} + +} +} diff --git a/src/standards/Tizen/Systeminfo/JSSysteminfo.h b/src/standards/Tizen/Systeminfo/JSSysteminfo.h new file mode 100755 index 0000000..8c67433 --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSSysteminfo.h @@ -0,0 +1,62 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_TIZEN1_0_JS_SYSTEMINFO_H_ +#define WRTPLUGINS_TIZEN1_0_JS_SYSTEMINFO_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSSysteminfoPriv; + +class JSSysteminfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + private: + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + + static JSValueRef isSupported(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef getPropertyValue(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef addPropertyValueChangedListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef removePropertyChangedListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSClassDefinition m_classInfo; + static JSStaticFunction m_function[]; + + static JSClassRef m_jsClassRef; +}; + +} +} + +#endif diff --git a/src/standards/Tizen/Systeminfo/JSWifiNetworkInfo.cpp b/src/standards/Tizen/Systeminfo/JSWifiNetworkInfo.cpp new file mode 100755 index 0000000..bab4245 --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSWifiNetworkInfo.cpp @@ -0,0 +1,137 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include "JSWifiNetworkInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace Api::Systeminfo; + +namespace { +const char* WIFINETWORK_STATUS_PROPERTY = "status"; +const char* WIFINETWORK_SSID_PROPERTY = "ssid"; +const char* WIFINETWORK_IPADDRESS_PROPERTY = "ipAddress"; +const char* WIFINETWORK_SIGNALSTRENGTH_PROPERTY = "signalStrength"; +} + +JSClassRef JSWifiNetworkInfo::m_classRef = NULL; + +JSClassDefinition JSWifiNetworkInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "wifinetworkinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSWifiNetworkInfo::m_properties[] = { + { WIFINETWORK_STATUS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { WIFINETWORK_SSID_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { WIFINETWORK_IPADDRESS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { WIFINETWORK_SIGNALSTRENGTH_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSWifiNetworkInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSWifiNetworkInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSWifiNetworkInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSWifiNetworkInfo::Finalize(JSObjectRef object) +{ + LogDebug("Entered"); + JSWifiNetworkPriv* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting WifiNetworkInfo object"); + delete priv; +} + +bool JSWifiNetworkInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSWifiNetworkInfo::createJSObject(JSContextRef context, const Api::Systeminfo::WifiNetworkProperties &wifiNetworkInfo) +{ + LogDebug("Enter"); + std::auto_ptr accProps(new Api::Systeminfo::WifiNetworkProperties(wifiNetworkInfo)); + JSWifiNetworkPriv *priv = new JSWifiNetworkPriv(context, accProps.get()); + accProps.release(); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSWifiNetworkInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("Enter"); + JSWifiNetworkPriv *priv = static_cast(JSObjectGetPrivate(object)); + if (NULL == priv) { + LogError("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + Api::Systeminfo::WifiNetworkProperties *wifiNetworkInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, WIFINETWORK_STATUS_PROPERTY)) { + return convert.toJSValueRef(wifiNetworkInfo->status); + } else if (JSStringIsEqualToUTF8CString(propertyName, WIFINETWORK_SSID_PROPERTY)) { + return convert.toJSValueRef(wifiNetworkInfo->ssid); + } else if (JSStringIsEqualToUTF8CString(propertyName, WIFINETWORK_IPADDRESS_PROPERTY)) { + return convert.toJSValueRef(wifiNetworkInfo->ipAddress); + } else if (JSStringIsEqualToUTF8CString(propertyName, WIFINETWORK_SIGNALSTRENGTH_PROPERTY)) { + return convert.toJSValueRef(wifiNetworkInfo->signalStrength); + } + } + Catch(Exception) + { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/src/standards/Tizen/Systeminfo/JSWifiNetworkInfo.h b/src/standards/Tizen/Systeminfo/JSWifiNetworkInfo.h new file mode 100755 index 0000000..0d765c4 --- /dev/null +++ b/src/standards/Tizen/Systeminfo/JSWifiNetworkInfo.h @@ -0,0 +1,49 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef WRTPLUGINS_TIZEN1_0_WIFINETWORK_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_WIFINETWORK_INFO_H_ + +#include +#include "API/Systeminfo/SysteminfoPropertyInfo.h" + +namespace TizenApis { +namespace Tizen1_0 { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type JSWifiNetworkPriv; + +class JSWifiNetworkInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const Api::Systeminfo::WifiNetworkProperties &wifiNetworkInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/src/standards/Tizen/Systeminfo/config.xml b/src/standards/Tizen/Systeminfo/config.xml new file mode 100755 index 0000000..da440d3 --- /dev/null +++ b/src/standards/Tizen/Systeminfo/config.xml @@ -0,0 +1,21 @@ + + + + libwrt-plugins-tizen-1.0-systeminfo.so + systeminfo.install.uri + SAMSUNG plugin group + SAMSUNG certificate authority + AAAABBBBCCCCDDDEEEE0000 + + + http://tizen.org/api/systeminfo + systeminfo + + + + + + + + + diff --git a/src/standards/Tizen/Systeminfo/plugin_config.cpp b/src/standards/Tizen/Systeminfo/plugin_config.cpp new file mode 100755 index 0000000..c244ecc --- /dev/null +++ b/src/standards/Tizen/Systeminfo/plugin_config.cpp @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include "plugin_config.h" + +#define SYSTEMINFO_FEATURE_API "http://tizen.org/api/systeminfo" + +#define SYSTEMINFO_DEVICE_CAP "systeminfo" + +namespace TizenApis { +namespace Tizen1_0 { + +const char* SYSTEMINFO_FUNCTION_API_IS_SUPPORTED = "isSupported"; +const char* SYSTEMINFO_FUNCTION_API_GET_PROPERTY_VALUE = "getPropertyValue"; +const char* SYSTEMINFO_FUNCTION_API_ADD_PROPERTY_VALUE_CHANGED_LISTENER = "addPropertyValueChangedListener"; +const char* SYSTEMINFO_FUNCTION_API_REMOVE_PROPERTY_CHANGED_LISTENER = "removePropertyChangedListener"; + +static WrtDeviceApis::Commons::FunctionMapping createSysteminfoFunctions(); + +static WrtDeviceApis::Commons::FunctionMapping SysteminfoFunctions = + createSysteminfoFunctions(); + +DEFINE_FUNCTION_GETTER(Systeminfo, SysteminfoFunctions); + +static WrtDeviceApis::Commons::FunctionMapping createSysteminfoFunctions() +{ + using namespace WrtDeviceApis::Commons; + + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_SYSTEMINFO, SYSTEMINFO_DEVICE_CAP); + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_SYSTEMINFO); + + ACE_ADD_DEVICE_CAP(DEVICE_LIST_SYSTEMINFO, DEVICE_CAP_SYSTEMINFO); + + ACE_CREATE_FEATURE(FEATURE_SYSTEMINFO, SYSTEMINFO_FEATURE_API); + ACE_CREATE_FEATURE_LIST(SYSTEMINFO_FEATURES); + + ACE_ADD_API_FEATURE(SYSTEMINFO_FEATURES, FEATURE_SYSTEMINFO); + + FunctionMapping SysteminfoFunctions; + + AceFunction isSupportedFunc = ACE_CREATE_FUNCTION( + FUNCTION_IS_SUPPORTED, + SYSTEMINFO_FUNCTION_API_IS_SUPPORTED, + SYSTEMINFO_FEATURES, + DEVICE_LIST_SYSTEMINFO); + + SysteminfoFunctions.insert(std::make_pair( + SYSTEMINFO_FUNCTION_API_IS_SUPPORTED, + isSupportedFunc)); + + + AceFunction getPropertyValueFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_PROPERTY_VALUE, + SYSTEMINFO_FUNCTION_API_GET_PROPERTY_VALUE, + SYSTEMINFO_FEATURES, + DEVICE_LIST_SYSTEMINFO); + + SysteminfoFunctions.insert(std::make_pair( + SYSTEMINFO_FUNCTION_API_GET_PROPERTY_VALUE, + getPropertyValueFunc)); + + + AceFunction addPropertyValueChangedListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_ADD_PROPERTY_VALUE_CHANGED_LISTENER, + SYSTEMINFO_FUNCTION_API_ADD_PROPERTY_VALUE_CHANGED_LISTENER, + SYSTEMINFO_FEATURES, + DEVICE_LIST_SYSTEMINFO); + + SysteminfoFunctions.insert(std::make_pair( + SYSTEMINFO_FUNCTION_API_ADD_PROPERTY_VALUE_CHANGED_LISTENER, + addPropertyValueChangedListenerFunc)); + + + AceFunction removePropertyChangedListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_REMOVE_PROPERTY_CHANGED_LISTENER, + SYSTEMINFO_FUNCTION_API_REMOVE_PROPERTY_CHANGED_LISTENER, + SYSTEMINFO_FEATURES, + DEVICE_LIST_SYSTEMINFO); + + SysteminfoFunctions.insert(std::make_pair( + SYSTEMINFO_FUNCTION_API_REMOVE_PROPERTY_CHANGED_LISTENER, + removePropertyChangedListenerFunc)); + + return SysteminfoFunctions; +} +} +} + +#undef SYSTEMINFO_FEATURE_API diff --git a/src/standards/Tizen/Systeminfo/plugin_config.h b/src/standards/Tizen/Systeminfo/plugin_config.h new file mode 100755 index 0000000..21fc071 --- /dev/null +++ b/src/standards/Tizen/Systeminfo/plugin_config.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _SYSTEMINFO_PLUGIN_CONFIG_H_ +#define _SYSTEMINFO_PLUGIN_CONFIG_H_ + +#include + +namespace TizenApis { +namespace Tizen1_0 { + +extern const char* SYSTEMINFO_FUNCTION_API_IS_SUPPORTED; +extern const char* SYSTEMINFO_FUNCTION_API_GET_PROPERTY_VALUE; +extern const char* SYSTEMINFO_FUNCTION_API_ADD_PROPERTY_VALUE_CHANGED_LISTENER; +extern const char* SYSTEMINFO_FUNCTION_API_REMOVE_PROPERTY_CHANGED_LISTENER; + +DECLARE_FUNCTION_GETTER(Systeminfo); + +#define SYSTEMINFO_CHECK_ACCESS(globalContext, functionName) \ + aceCheckAccess >( \ + globalContext, \ + getSysteminfoFunctionData, \ + functionName) +} +} + +#endif \ No newline at end of file diff --git a/src/standards/Tizen/Systeminfo/plugin_initializer.cpp b/src/standards/Tizen/Systeminfo/plugin_initializer.cpp new file mode 100755 index 0000000..6a6d34f --- /dev/null +++ b/src/standards/Tizen/Systeminfo/plugin_initializer.cpp @@ -0,0 +1,41 @@ +/* + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include "JSSysteminfo.h" + +#define WRT_JS_EXTENSION_OBJECT_TIZEN "tizen" + +void on_widget_start_callback(int widgetId, JavaScriptContext context, const engine_interface_t *interface) +{ + LogDebug("[Tizen\\Systeminfo ] on_widget_start_callback (" << widgetId << ")"); +} + +void on_widget_stop_callback(int widgetId) +{ + LogDebug("[Tizen\\Systeminfo ] on_widget_stop_callback (" << widgetId << ")"); +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, "systeminfo", TizenApis::Tizen1_0::JSSysteminfo::getClassRef(), NULL) +PLUGIN_CLASS_MAP_END + diff --git a/src/standards/Tizen/TimeUtil/CMakeLists.txt b/src/standards/Tizen/TimeUtil/CMakeLists.txt new file mode 100755 index 0000000..1c72204 --- /dev/null +++ b/src/standards/Tizen/TimeUtil/CMakeLists.txt @@ -0,0 +1,26 @@ +set(TARGET_NAME "wrt-plugins-tizen-1.0-time") + +include_directories(${INCLUDES_PLATFORM_IMPLEMENTATION_TIMEUTIL}) + +set(SRCS + ${SRCS_PLATFORM_API_TIMEUTIL} + ${SRCS_PLATFORM_IMPLEMENTATION_TIMEUTIL} + JSTimeUtil.cpp + JSTZDate.cpp + TimeUtilConverter.cpp + plugin_initializer.cpp + plugin_config.cpp +../Common/JSTizenException.cpp +../Common/TizenExceptionData.cpp +../Common/JSTizenExceptionFactory.cpp +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + wrt-plugins-tizen-1.0-tizen + ${LIBS_COMMON} + ${LIBS_PLATFORM_IMPLEMENTATION_TIMEUTIL} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION tizen-1.0-time) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION tizen-1.0-time) diff --git a/src/standards/Tizen/TimeUtil/JSTZDate.cpp b/src/standards/Tizen/TimeUtil/JSTZDate.cpp new file mode 100755 index 0000000..052c1b0 --- /dev/null +++ b/src/standards/Tizen/TimeUtil/JSTZDate.cpp @@ -0,0 +1,1620 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include "JSTZDate.h" +#include "TimeUtilConverter.h" +#include "plugin_config.h" + +using namespace TizenApis::Api::TimeUtil; +using namespace TizenApis::Commons; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +#define min(a,b) (((a) < (b)) ? (a) : (b)) + +#define TIZEN10_TZDATE_ATTRIBUTENAME "TZDate" + +namespace TizenApis { +namespace Tizen1_0 { + +JSClassDefinition JSTZDate::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN10_TZDATE_ATTRIBUTENAME, + 0, + NULL,//property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + constructor, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticFunction JSTZDate::m_function[] = { + {"getDate", JSTZDate::getDate, kJSPropertyAttributeNone}, + {"getDay", JSTZDate::getDay, kJSPropertyAttributeNone}, + {"getFullYear", JSTZDate::getFullYear, kJSPropertyAttributeNone}, + {"getHours", JSTZDate::getHours, kJSPropertyAttributeNone}, + {"getMilliseconds", JSTZDate::getMilliseconds, kJSPropertyAttributeNone}, + {"getMinutes", JSTZDate::getMinutes, kJSPropertyAttributeNone}, + {"getMonth", JSTZDate::getMonth, kJSPropertyAttributeNone}, + {"getSeconds", JSTZDate::getSeconds, kJSPropertyAttributeNone}, + + {"setDate", JSTZDate::setDate, kJSPropertyAttributeNone}, + {"setFullYear", JSTZDate::setFullYear, kJSPropertyAttributeNone}, + {"setHours", JSTZDate::setHours, kJSPropertyAttributeNone}, + {"setMilliseconds", JSTZDate::setMilliseconds, kJSPropertyAttributeNone}, + {"setMinutes", JSTZDate::setMinutes, kJSPropertyAttributeNone}, + {"setMonth", JSTZDate::setMonth, kJSPropertyAttributeNone}, + {"setSeconds", JSTZDate::setSeconds, kJSPropertyAttributeNone}, + + {"getUTCDate", JSTZDate::getUTCDate, kJSPropertyAttributeNone}, + {"getUTCDay", JSTZDate::getUTCDay, kJSPropertyAttributeNone}, + {"getUTCFullYear", JSTZDate::getUTCFullYear, kJSPropertyAttributeNone}, + {"getUTCHours", JSTZDate::getUTCHours, kJSPropertyAttributeNone}, + {"getUTCMilliseconds", JSTZDate::getUTCMilliseconds, kJSPropertyAttributeNone}, + {"getUTCMinutes", JSTZDate::getUTCMinutes, kJSPropertyAttributeNone}, + {"getUTCMonth", JSTZDate::getUTCMonth, kJSPropertyAttributeNone}, + {"getUTCSeconds", JSTZDate::getUTCSeconds, kJSPropertyAttributeNone}, + + {"setUTCDate", JSTZDate::setUTCDate, kJSPropertyAttributeNone}, + {"setUTCFullYear", JSTZDate::setUTCFullYear, kJSPropertyAttributeNone}, + {"setUTCHours", JSTZDate::setUTCHours, kJSPropertyAttributeNone}, + {"setUTCMilliseconds", JSTZDate::setUTCMilliseconds, kJSPropertyAttributeNone}, + {"setUTCMinutes", JSTZDate::setUTCMinutes, kJSPropertyAttributeNone}, + {"setUTCMonth", JSTZDate::setUTCMonth, kJSPropertyAttributeNone}, + {"setUTCSeconds", JSTZDate::setUTCSeconds, kJSPropertyAttributeNone}, + + {"getTimezone", JSTZDate::getTimezone, kJSPropertyAttributeNone}, + {"toTimezone", JSTZDate::toTimezone, kJSPropertyAttributeNone}, + {"toLocalTimezone", JSTZDate::toLocalTimezone, kJSPropertyAttributeNone}, + {"toUTC", JSTZDate::toUTC, kJSPropertyAttributeNone}, + + {"difference", JSTZDate::difference, kJSPropertyAttributeNone}, + {"equalsTo", JSTZDate::equalsTo, kJSPropertyAttributeNone}, + {"earlierThan", JSTZDate::earlierThan, kJSPropertyAttributeNone}, + {"laterThan", JSTZDate::laterThan, kJSPropertyAttributeNone}, + {"addDuration", JSTZDate::addDuration, kJSPropertyAttributeNone}, + + {"toLocaleDateString", JSTZDate::toLocaleDateString, kJSPropertyAttributeNone}, + {"toLocaleTimeString", JSTZDate::toLocaleTimeString, kJSPropertyAttributeNone}, + {"toLocaleString", JSTZDate::toLocaleString, kJSPropertyAttributeNone}, + {"toDateString", JSTZDate::toDateString, kJSPropertyAttributeNone}, + {"toTimeString", JSTZDate::toTimeString, kJSPropertyAttributeNone}, + {"toString", JSTZDate::toString, kJSPropertyAttributeNone}, + + {"getTimezoneAbbreviation", JSTZDate::getTimezoneAbbreviation, kJSPropertyAttributeNone}, + {"secondsFromUTC", JSTZDate::secondsFromUTC, kJSPropertyAttributeNone}, + {"isDST", JSTZDate::isDST, kJSPropertyAttributeNone}, + {"getPreviousDSTTransition", JSTZDate::getPreviousDSTTransition, kJSPropertyAttributeNone}, + {"getNextDSTTransition", JSTZDate::getNextDSTTransition, kJSPropertyAttributeNone}, + { 0, 0, 0} +}; + +JSClassRef JSTZDate::m_jsClassRef = JSClassCreate(JSTZDate::getClassInfo()); + +JSObjectRef JSTZDate::createJSObject(JSContextRef context) { + LogDebug("entered"); + ITZDatePtr TZDate = TimeUtilFactory::getInstance().createTZDateObject(); + TZDatePrivObject *priv = new TZDatePrivObject(context, TZDate); + if (!priv) { + ThrowMsg(NullPointerException, "Can not new an object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + +JSObjectRef JSTZDate::createJSObject(JSContextRef context, const TZDateProperties &properties) { + LogDebug("entered"); + ITZDatePtr TZDate = TimeUtilFactory::getInstance().createTZDateObject(properties); + + TZDatePrivObject *priv = new TZDatePrivObject(context, TZDate); + if (!priv) { + ThrowMsg(NullPointerException, "Can not new an object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + +JSObjectRef JSTZDate::createJSObject(JSContextRef context, const long year, const long month, const long day, const long hours, const long minutes, const long seconds, const std::string &timezone) { + LogDebug("entered"); + + TZDateProperties props; + props.year = year; + props.month = month; + props.day = day; + props.hours = hours; + props.minutes = minutes; + props.seconds = seconds; + props.timezone = timezone; + + return createJSObject(context, props); + +} + +JSObjectRef JSTZDate::createJSObject(JSContextRef context, const time_t localTime, const std::string &timezone) { + LogDebug("entered"); + + struct tm *tm = localtime(&localTime); + + return createJSObject(context, tm->tm_year + 1900, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, timezone); +} + +void JSTZDate::initialize(JSContextRef context, JSObjectRef object) +{ + LogDebug("entered Nothing to do."); + + if (!JSObjectGetPrivate(object)) { + LogDebug("Private object not set... setting it."); + ITZDatePtr TZDate = TimeUtilFactory::getInstance().createTZDateObject(FALSE); + TZDatePrivObject *priv = new TZDatePrivObject(context, TZDate); + if (!JSObjectSetPrivate(object, priv)) { + delete priv; + } + } +} + +void JSTZDate::finalize(JSObjectRef object) +{ + LogDebug( "entered" ); + TZDatePrivObject *priv = + static_cast( JSObjectGetPrivate( object ) ) ; + delete priv; +} + +JSObjectRef JSTZDate::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + LogDebug("entered"); + TZDateProperties prop; + TimeUtilConverter converter(ctx); + + TZDatePrivObject* mainPriv = static_cast(JSObjectGetPrivate(constructor)); + JSContextRef global_context = mainPriv ? mainPriv->getContext() : ctx; + Try { + if (argumentCount == 0) { + return createJSObject(global_context); + } else if (argumentCount <= 2) { + if (!JSValueIsNull(ctx, arguments[0]) && !JSValueIsUndefined(ctx, arguments[0])) { + std::time_t date; + date = converter.toDateTimeT(arguments[0]); + std::string timezone = ""; + if (argumentCount > 1) { + if ( JSValueIsNull(ctx, arguments[1]) || JSValueIsUndefined(ctx, arguments[1]) || !JSValueIsString(ctx, arguments[1])) + ThrowMsg(InvalidArgumentException, "Argument is invalid"); + timezone = converter.toString(arguments[1]); + } + return createJSObject(global_context, date, timezone); + } + } else { + prop.year = converter.FromJSValueReftolong(arguments[0]); + prop.month = converter.FromJSValueReftolong(arguments[1]); + prop.day = converter.FromJSValueReftolong(arguments[2]); + if (argumentCount > 3) { + if ((JSValueIsNull(ctx, arguments[3]) || JSValueIsUndefined(ctx, arguments[3])) + || !(JSValueIsNumber(ctx, arguments[3]))) { + ThrowMsg(InvalidArgumentException, "Argument is invalid"); + } + prop.hours = converter.FromJSValueReftolong(arguments[3]); + if (argumentCount > 4) { + if (JSValueIsNull(ctx, arguments[4]) || JSValueIsUndefined(ctx, arguments[4]) || !JSValueIsNumber(ctx, arguments[4])) { + ThrowMsg(InvalidArgumentException, "Argument is invalid"); + } + prop.minutes = converter.FromJSValueReftolong(arguments[4]); + if (argumentCount > 5) { + if (JSValueIsNull(ctx, arguments[5]) || JSValueIsUndefined(ctx, arguments[5]) || !JSValueIsNumber(ctx, arguments[5])) { + ThrowMsg(InvalidArgumentException, "Argument is invalid"); + } + prop.seconds = converter.FromJSValueReftolong(arguments[5]); + if (argumentCount > 6) { + if (JSValueIsNull(ctx, arguments[6]) || JSValueIsUndefined(ctx, arguments[6]) || !JSValueIsNumber(ctx, arguments[6])) { + ThrowMsg(InvalidArgumentException, "Argument is invalid"); + } + prop.milliseconds= converter.FromJSValueReftolong(arguments[6]); + if (argumentCount > 7) { + if (JSValueIsNull(ctx, arguments[7]) || JSValueIsUndefined(ctx, arguments[7]) || !JSValueIsString(ctx, arguments[7])) { + ThrowMsg(InvalidArgumentException, "Argument is invalid"); + } + prop.timezone = converter.toString(arguments[7]); + } + } + } + } + } + return createJSObject(global_context, prop); + } + ThrowMsg(InvalidArgumentException, "Wrong TZDate argumentCount"); + } Catch(ConversionException) { + LogDebug("Wrong conversion"); + return converter.toJSObjectRef(JSTizenExceptionFactory::makeErrorObject(ctx, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch")); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return converter.toJSObjectRef(JSTizenExceptionFactory::makeErrorObject(ctx, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value")); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LogWarning("Trying to get incorrect value"); + } + return converter.toJSObjectRef(JSTizenExceptionFactory::makeErrorObject(ctx, JSTizenException::UNKNOWN_ERROR, "Unknown Error")); +} +const JSClassRef JSTZDate::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSTZDate::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSTZDate::getTimezone(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("entered"); + + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ITZDatePtr TZDate(privateObject->getObject()); + std::string timezone = TZDate->getTimezone(); + TimeUtilConverter converter(context); + + return converter.toJSValueRef(timezone); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSTZDate::toTimezone(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("entered"); + + TimeUtilConverter converter(context); + + Try { + if ((argumentCount < 1) ||(JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0])) + || (!JSValueIsString(context, arguments[0]))) { + LogError("Wrong TZDate parameters"); + ThrowMsg(InvalidArgumentException, "Wrong TZDate parameters"); + } + + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + std::string timezone = converter.toString(arguments[0]); + ITZDatePtr TZDate(privateObject->getObject()); + return createJSObject(context, TZDate->toTimezone(timezone)); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSTZDate::diffTZDate(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception, CompareType type) { + LogDebug("entered"); + + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + + TimeUtilConverter converter(context); + + if ((argumentCount < 1) ||(JSValueIsNull(context, arguments[0]) || JSValueIsUndefined(context, arguments[0])) + || (!JSValueIsObjectOfClass(context, arguments[0], getClassRef()))) { + LogError("Wrong TZDate parameters"); + ThrowMsg(InvalidArgumentException, "Wrong TZDate parameters"); + } + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + ITZDatePtr TZDate(privateObject->getObject()); + long long cmpResult = TZDate->difference(converter.getPropertiesInTZDate(arguments[0])); + + switch (type) { + case EQUALSTO: + { + if (cmpResult == 0) + return converter.toJSValueRef(TRUE); + else + return converter.toJSValueRef(FALSE); + } + case EARLIERTHAN: + { + if (cmpResult < 0) + return converter.toJSValueRef(TRUE); + else + return converter.toJSValueRef(FALSE); + } + case LATERTHAN: + { + if (cmpResult > 0) + return converter.toJSValueRef(TRUE); + else + return converter.toJSValueRef(FALSE); + } + case DIFFERENCE: + default: + return converter.makeMillisecondDurationObject(cmpResult); + } +} + +JSValueRef JSTZDate::difference(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("entered"); + + Try { + return diffTZDate(context, thisObject, argumentCount, arguments, exception, DIFFERENCE); + } Catch(InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSTZDate::equalsTo(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("entered"); + + Try { + return diffTZDate(context, thisObject, argumentCount, arguments, exception, EQUALSTO); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSTZDate::earlierThan(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("earlierThan entered"); + + Try { + return diffTZDate(context, thisObject, argumentCount, arguments, exception, EARLIERTHAN); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); + +} + +JSValueRef JSTZDate::laterThan(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + + LogDebug("laterThan entered"); + + Try { + return diffTZDate(context, thisObject, argumentCount, arguments, exception, LATERTHAN); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); + +} + +JSValueRef JSTZDate::addDuration(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + + LogDebug("addDuration entered"); + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TimeUtilConverter converter(context); + + DurationProperties duration = converter.getDurationPropertis(arguments[0], exception); + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ITZDatePtr TZDate(privateObject->getObject()); + TZDateProperties result = TZDate->addDuration(duration); + return (static_cast(createJSObject(privateObject->getContext(), result))); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSTZDate::toUTC(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + + LogDebug("toUTC entered"); + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ITZDatePtr TZDate(privateObject->getObject()); + TZDateProperties result = TZDate->toUTC(); + return (static_cast(createJSObject(privateObject->getContext(), result))); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSTZDate::toLocalTimezone(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + + LogDebug("toLocalTimezone entered"); + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ITZDatePtr TZDate(privateObject->getObject()); + TZDateProperties result = TZDate->toLocalTimezone(); + return (static_cast(createJSObject(privateObject->getContext(), result))); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSTZDate::toLocaleDateString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + ITZDatePtr TZDate(privateObject->getObject()); + std::string result = TZDate->toDateString(true); + return converter.toJSValueRef(result); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } +} + +JSValueRef JSTZDate::toLocaleTimeString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + ITZDatePtr TZDate(privateObject->getObject()); + std::string result = TZDate->toTimeString(true); + return converter.toJSValueRef(result); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } +} + +JSValueRef JSTZDate::toLocaleString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + ITZDatePtr TZDate(privateObject->getObject()); + std::string result = TZDate->toString(true); + return converter.toJSValueRef(result); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } +} + +JSValueRef JSTZDate::toDateString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + ITZDatePtr TZDate(privateObject->getObject()); + std::string result = TZDate->toDateString(); + return converter.toJSValueRef(result); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } +} + +JSValueRef JSTZDate::toTimeString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + ITZDatePtr TZDate(privateObject->getObject()); + std::string result = TZDate->toTimeString(); + return converter.toJSValueRef(result); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } +} + + +JSValueRef JSTZDate::toString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + ITZDatePtr TZDate(privateObject->getObject()); + std::string result = TZDate->toString(); + return converter.toJSValueRef(result); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } +} + +JSValueRef JSTZDate::getDate(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_DATE; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getDate() + +JSValueRef JSTZDate::getDay(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_DAY_OF_WEEK; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getDay() + +JSValueRef JSTZDate::getFullYear(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_YEAR; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getFullYear() + +JSValueRef JSTZDate::getHours(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_HOUR_OF_DAY; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getHours() + +JSValueRef JSTZDate::getMilliseconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_MILLISECOND; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getMilliseconds() + +JSValueRef JSTZDate::getMinutes(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_MINUTE; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getMinutes() + +JSValueRef JSTZDate::getMonth(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_MONTH; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getMonth() + +JSValueRef JSTZDate::getSeconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_SECOND; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getSeconds() + +JSValueRef JSTZDate::getTZDateValue(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception, + ITZDate::TZDateFields dateFields) { + try { + TZDatePrivObject* privateObject = static_cast (JSObjectGetPrivate(thisObject)); + + if (privateObject == NULL) { + LogError(">>> NULL Exception"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ITZDatePtr tzDate(privateObject->getObject()); + long retVal = tzDate->get(dateFields); + + TimeUtilConverter converter(context); + LogDebug(">>> retVal:" << retVal); + return converter.toJSValueRef(static_cast (retVal)); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } +} + +JSValueRef JSTZDate::setDate(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + int minData = 1; + int maxData = 31; + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_DATE; + size_t argumentIndex = 0; + + try{ + setTZDateValue(context, thisObject, argumentCount, arguments, argumentIndex, exception, dateFields, minData, maxData); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeUndefined(context); +} //setDate() + +JSValueRef JSTZDate::setFullYear(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + int minData = 1000; + int maxData = 9999; + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_YEAR; + size_t argumentIndex = 0; + + try{ + setTZDateValue(context, thisObject, argumentCount, arguments, argumentIndex, exception, dateFields, minData, maxData); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeUndefined(context); +} //setFullYear() + +JSValueRef JSTZDate::setHours(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + int minData = 0; + int maxData = 23; + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_HOUR_OF_DAY; + size_t argumentIndex = 0; + + Try { + setTZDateValue(context, thisObject, argumentCount, arguments, argumentIndex, exception, dateFields, minData, maxData); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeUndefined(context); +} //setHours() + +JSValueRef JSTZDate::setMilliseconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + int minData = 0; + int maxData = 999; + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_MILLISECOND; + size_t argumentIndex = 0; + + Try{ + setTZDateValue(context, thisObject, argumentCount, arguments, argumentIndex, exception, dateFields, minData, maxData); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeUndefined(context); +} //setMilliseconds() + +JSValueRef JSTZDate::setMinutes(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + int minData = 0; + int maxData = 23; + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_MINUTE; + size_t argumentIndex = 0; + + Try { + setTZDateValue(context, thisObject, argumentCount, arguments, argumentIndex, exception, dateFields, minData, maxData); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeUndefined(context); +} //setMinutes() + +JSValueRef JSTZDate::setMonth(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + int minData = 0; + int maxData = 11; + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_MONTH; + size_t argumentIndex = 0; + + Try { + setTZDateValue(context, thisObject, argumentCount, arguments, argumentIndex, exception, dateFields, minData, maxData); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeUndefined(context); +} //setMonth() + +JSValueRef JSTZDate::setSeconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LogDebug("<<<"); + + int minData = 0; + int maxData = 23; + ITZDate::TZDateFields dateFields = ITZDate::TZDATE_SECOND; + size_t argumentIndex = 0; + + Try { + setTZDateValue(context, thisObject, argumentCount, arguments, argumentIndex, exception, dateFields, minData, maxData); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeUndefined(context); +} //setSeconds() + + +JSValueRef JSTZDate::setTZDateValue(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], size_t argumentIndex, + JSValueRef * exception, ITZDate::TZDateFields dateFields, int minData, int maxData) { + + if (argumentCount - 1 < argumentIndex) { + LogError("Wrong parameters"); + ThrowMsg(InvalidArgumentException, "argumentIndex is bigger than argumentCount"); + } + + TimeUtilConverter converter(context); + + int data = converter.toInt(arguments[argumentIndex]); + LogDebug("input data:" << data << ", minData:" << minData << ", maxData" << maxData); + + if (data < minData || data > maxData) { + LogError("Wrong parameters data:" << data); + ThrowMsg(InvalidArgumentException, "data range missmatch"); + } + + TZDatePrivObject* privateObject = static_cast (JSObjectGetPrivate(thisObject)); + + if (privateObject == NULL) { + LogError(">>> NULL Exception"); + ThrowMsg(UnknownException, "privateObject is NULL"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ITZDatePtr tzDate(privateObject->getObject()); + tzDate->set(dateFields, static_cast (data)); + + return JSValueMakeUndefined(context); +} //setTZDateValue + +JSValueRef JSTZDate::getUTCDate(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + return getUTCTZDateValue(context, thisObject, ITZDate::TZDATE_DATE, exception); +} + +JSValueRef JSTZDate::getUTCDay(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + return getUTCTZDateValue(context, thisObject, ITZDate::TZDATE_DAY_OF_WEEK, exception); +} + +JSValueRef JSTZDate::getUTCFullYear(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + return getUTCTZDateValue(context, thisObject, ITZDate::TZDATE_YEAR, exception); +} + +JSValueRef JSTZDate::getUTCHours(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + return getUTCTZDateValue(context, thisObject, ITZDate::TZDATE_HOUR_OF_DAY, exception); +} + +JSValueRef JSTZDate::getUTCMilliseconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + return getUTCTZDateValue(context, thisObject, ITZDate::TZDATE_MILLISECOND, exception); +} + +JSValueRef JSTZDate::getUTCMinutes(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + return getUTCTZDateValue(context, thisObject, ITZDate::TZDATE_MINUTE, exception); +} + +JSValueRef JSTZDate::getUTCMonth(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + return getUTCTZDateValue(context, thisObject, ITZDate::TZDATE_MONTH, exception); +} + +JSValueRef JSTZDate::getUTCSeconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + return getUTCTZDateValue(context, thisObject, ITZDate::TZDATE_SECOND, exception); +} + +JSValueRef JSTZDate::getUTCTZDateValue(JSContextRef context, JSObjectRef thisObject, ITZDate::TZDateFields DateFields, JSValueRef * exception) { + LogDebug("Entered"); + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + ITZDatePtr TZDate(privateObject->getObject()); + long result = TZDate->getUTC(DateFields); + + return converter.toJSValueRefLong(result); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } +} + +JSValueRef JSTZDate::setUTCDate(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, ITZDate::TZDATE_DATE, exception, 1, 31); +} + +JSValueRef JSTZDate::setUTCFullYear(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, ITZDate::TZDATE_YEAR, exception, 1000, 9999); +} + +JSValueRef JSTZDate::setUTCHours(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, ITZDate::TZDATE_HOUR_OF_DAY, exception, 0, 23); +} + +JSValueRef JSTZDate::setUTCMilliseconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, ITZDate::TZDATE_MILLISECOND, exception, 0, 999); +} + +JSValueRef JSTZDate::setUTCMinutes(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, ITZDate::TZDATE_MINUTE, exception, 0, 59); +} + +JSValueRef JSTZDate::setUTCMonth(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, ITZDate::TZDATE_MONTH, exception, 0, 11); +} + +JSValueRef JSTZDate::setUTCSeconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, ITZDate::TZDATE_SECOND, exception, 0, 59); +} + +JSValueRef JSTZDate::setUTCTZDateValue(JSContextRef context, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], ITZDate::TZDateFields dateFields, JSValueRef * exception, int minData, int maxData) { + LogDebug("Entered"); + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + if ((argumentCount < 1) + || (!JSValueIsNumber(context, arguments[0]))) + { + LogError("Wrong TZDate parameters"); + ThrowMsg(InvalidArgumentException, "Wrong TZDate parameters"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + long data = converter.FromJSValueReftolong(arguments[0]); + if (data < minData || data > maxData) { + LogError("Wrong parameters data:" << data); + ThrowMsg(InvalidArgumentException, "data range missmatch"); + } + ITZDatePtr TZDate(privateObject->getObject()); + TZDate->setUTC(dateFields, data); + + return JSValueMakeUndefined(context); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } +} + +JSValueRef JSTZDate::getTimezoneAbbreviation(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("entered"); + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + ITZDatePtr tzDate(privateObject->getObject()); + + std::string result; + + return converter.toJSValueRef(tzDate->getTimezoneAbbreviation()); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSTZDate::secondsFromUTC(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("entered"); + + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + ITZDatePtr tzDate(privateObject->getObject()); + + return converter.toJSValueRefLong(tzDate->secondsFromUTC()); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} +JSValueRef JSTZDate::isDST(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("entered"); + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + ITZDatePtr tzDate(privateObject->getObject()); + + return converter.toJSValueRef(tzDate->isDST()); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSTZDate::getPreviousDSTTransition(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("entered"); + + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + ITZDatePtr tzDate(privateObject->getObject()); + + return createJSObject(privateObject->getContext(), tzDate->getDSTTransition(ITZDate::PREV_TRANSITION)); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSTZDate::getNextDSTTransition(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("entered"); + + Try { + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + ITZDatePtr tzDate(privateObject->getObject()); + + return createJSObject(privateObject->getContext(), tzDate->getDSTTransition(ITZDate::NEXT_TRANSITION)); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(UnknownException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeUndefined(context); +} + +} //Tizen1_0 +} //TizenApis +#undef min diff --git a/src/standards/Tizen/TimeUtil/JSTZDate.h b/src/standards/Tizen/TimeUtil/JSTZDate.h new file mode 100755 index 0000000..71e9b48 --- /dev/null +++ b/src/standards/Tizen/TimeUtil/JSTZDate.h @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#ifndef _JS_TIZEN_TZDATE_H_ +#define _JS_TIZEN_TZDATE_H_ + +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject TZDatePrivObject; + +class JSTZDate +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context); + static JSObjectRef createJSObject(JSContextRef context, const Api::TimeUtil::TZDateProperties &properties); + static JSObjectRef createJSObject(JSContextRef context, const time_t localTime, const std::string &timezone); + static JSObjectRef createJSObject(JSContextRef context, const long year, const long month, const long day, const long hours, const long minutes, const long seconds, const std::string &timezone); +private: + enum CompareType { + DIFFERENCE, + EQUALSTO, + EARLIERTHAN, + LATERTHAN + }; + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef getTimezone(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toTimezone(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + + static JSValueRef diffTZDate(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception, CompareType type); + + static JSValueRef difference(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef equalsTo(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef earlierThan(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef laterThan(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef addDuration(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toUTC(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toLocalTimezone(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + + static JSValueRef toLocaleDateString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toLocaleTimeString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toLocaleString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toDateString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toTimeString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + + static JSValueRef getDate(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getDay(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getFullYear(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getHours(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getMilliseconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getMinutes(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getMonth(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getSeconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setTZDateValue(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], size_t argumentIndex, JSValueRef * exception, + TizenApis::Api::TimeUtil::ITZDate::TZDateFields dateFields, int minData, int maxData); + + static JSValueRef getTZDateValue(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception, + TizenApis::Api::TimeUtil::ITZDate::TZDateFields dateFields); + + static JSValueRef setDate(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setFullYear(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setHours(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setMilliseconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setMinutes(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setMonth(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setSeconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getUTCTZDateValue(JSContextRef context, JSObjectRef thisObject, + TizenApis::Api::TimeUtil::ITZDate::TZDateFields DateFields, JSValueRef * exception); + static JSValueRef getUTCDate(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCDay(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCFullYear(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCHours(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCMilliseconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCMinutes(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCMonth(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCSeconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + + static JSValueRef setUTCTZDateValue(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], TizenApis::Api::TimeUtil::ITZDate::TZDateFields dateFields, JSValueRef * exception, int minData, int maxData); + static JSValueRef setUTCDate(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef setUTCFullYear(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef setUTCHours(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef setUTCMilliseconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef setUTCMinutes(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef setUTCMonth(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef setUTCSeconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + + static JSValueRef getTimezoneAbbreviation(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef secondsFromUTC(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef isDST(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getPreviousDSTTransition(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getNextDSTTransition(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); +}; + +} +} + +#endif /* _JS_TIZEN_DATETIME_H_ */ diff --git a/src/standards/Tizen/TimeUtil/JSTimeUtil.cpp b/src/standards/Tizen/TimeUtil/JSTimeUtil.cpp new file mode 100755 index 0000000..c45cf2d --- /dev/null +++ b/src/standards/Tizen/TimeUtil/JSTimeUtil.cpp @@ -0,0 +1,487 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include "JSTimeUtil.h" +#include "JSTZDate.h" +#include "TimeUtilConverter.h" +#include "plugin_config.h" + +namespace TizenApis { +namespace Tizen1_0 { + +using namespace DPL; +using namespace TizenApis::Api::TimeUtil; +using namespace TizenApis::Commons; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +JSClassDefinition JSTimeUtil::m_classInfo = { + 0, + kJSClassAttributeNone, + "TimeUtil", + 0, + NULL, + m_function, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, + NULL, //ConvertToType +}; + +JSStaticFunction JSTimeUtil::m_function[] = { + { "getCurrentDateTime", JSTimeUtil::getCurrentDateTime, kJSPropertyAttributeNone }, + { "setCurrentDateTime", JSTimeUtil::setCurrentDateTime, kJSPropertyAttributeNone }, + { "getLocalTimezone", JSTimeUtil::getLocalTimezone, kJSPropertyAttributeNone }, + { "getAvailableTimezones", JSTimeUtil::getAvailableTimezones, kJSPropertyAttributeNone }, + { "getDateFormat", JSTimeUtil::getDateFormat, kJSPropertyAttributeNone }, + { "getTimeFormat", JSTimeUtil::getTimeFormat, kJSPropertyAttributeNone }, + { "isLeapYear", JSTimeUtil::isLeapYear, kJSPropertyAttributeNone}, + { "durationDifference", JSTimeUtil::durationDifference, kJSPropertyAttributeNone}, + { 0, 0, 0 } +}; + +const JSClassRef JSTimeUtil::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSTimeUtil::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSTimeUtil::m_jsClassRef = JSClassCreate(JSTimeUtil::getClassInfo()); + +void JSTimeUtil::initialize(JSContextRef context, JSObjectRef object) +{ + TimeUtilPrivObject* priv = static_cast(JSObjectGetPrivate(object)); + if (!priv) { + ITimeUtilPtr TimeUtil( TimeUtilFactory::getInstance().createTimeUtilObject() ); + priv = new TimeUtilPrivObject( context, TimeUtil); + if(!JSObjectSetPrivate(object, static_cast(priv))) { + LogError("Object can't store private data."); + delete priv; + } + } + + LogDebug("JSTimeUtil::initialize "); +} + +void JSTimeUtil::finalize(JSObjectRef object) +{ + TimeUtilPrivObject* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LogDebug("Deleting TimeUtil"); + delete priv; +} + +bool JSTimeUtil::hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSTimeUtil::getCurrentDateTime(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + Try { + TimeUtilPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + return JSTZDate::createJSObject(privateObject->getContext()); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSTimeUtil::setCurrentDateTime(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + + TimeUtilPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LogError("private object is null"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_SET_CURRENT_DATE_TIME); + + Try { + if (argumentCount < 1) { + Throw(InvalidArgumentException); + } + + TimeUtilConverter converter(context); + + if (JSValueIsUndefined(context, arguments[0]) || JSValueIsNull(context, arguments[0]) + || (!JSValueIsObjectOfClass(context, arguments[0], JSTZDate::getClassRef()))) { + LogError("Wrong event argument"); + Throw(InvalidArgumentException); + } + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ITimeUtilPtr TimeUtil(privateObject->getObject()); + + TZDateProperties TZDate = converter.getPropertiesInTZDate(arguments[0]); + + TimeUtil->setCurrentTZDate(TZDate); + + return JSValueMakeNull(context); + } Catch(ConversionException) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (InvalidArgumentException) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value"); + } Catch (UnsupportedException) { + LogError("JSTimeUtil::hasInstance NotSupportedException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::PERMISSION_DENIED_ERROR , "Permission Denied"); + } Catch(WrtDeviceApis::Commons::Exception) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSTimeUtil::getLocalTimezone(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Entered "); + Try { + TimeUtilPrivObject* privateObject = + static_cast(JSObjectGetPrivate( + thisObject)); + if (NULL == privateObject) { + ThrowMsg(NullPointerException, "Can not new an object"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ITimeUtilPtr TimeUtil(privateObject->getObject()); + std::string localTimezone = TimeUtil->getLocalTimezone(); + + TimeUtilConverter converter(context); + + return converter.toJSValueRef(localTimezone); + } Catch(NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSTimeUtil::getAvailableTimezones(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try { + TimeUtilPrivObject* privateObject = + static_cast(JSObjectGetPrivate( + thisObject)); + if (NULL == privateObject) { + ThrowMsg(NullPointerException, "Can not new an object"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + ITimeUtilPtr TimeUtil(privateObject->getObject()); + + std::vector timezones = TimeUtil->getAvailableTimezones(); + std::vector timezonesArray; + unsigned short timezonesCount = timezones.size(); + for (int i = 0; i < timezonesCount; ++i) { + timezonesArray.push_back(converter.toJSValueRef(timezones[i])); + } + + return converter.toJSValueRef(timezonesArray); + } Catch(ConversionException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value");; + } Catch (UnsupportedException) { + LogError("JSTimeUtil::hasInstance NotSupportedException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::NOT_SUPPORTED_ERROR , "Not Support"); + } Catch (NullPointerException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSTimeUtil::getDateFormat(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try { + TimeUtilPrivObject* privateObject = + static_cast(JSObjectGetPrivate( + thisObject)); + bool b_shortFormat = true; + + if (NULL == privateObject) { + Throw(WrtDeviceApis::Commons::Exception); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if ((argumentCount == 0) || (JSValueIsNull(context, arguments[0]))) { + b_shortFormat = false; + } else if (JSValueIsUndefined(context, arguments[0]) || !JSValueIsBoolean(context, arguments[0])) + Throw(InvalidArgumentException); + + ITimeUtilPtr TimeUtil(privateObject->getObject()); + std::string dateformat = TimeUtil->getDateFormat(b_shortFormat); + TimeUtilConverter converter(context); + + return converter.toJSValueRef(dateformat); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value");; + } Catch (UnsupportedException) { + LogError("JSTimeUtil::hasInstance NotSupportedException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::NOT_SUPPORTED_ERROR , "Not Support"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSTimeUtil::getTimeFormat(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("entered"); + Try { + TimeUtilPrivObject* privateObject = + static_cast(JSObjectGetPrivate( + thisObject)); + + if (NULL == privateObject) { + Throw(WrtDeviceApis::Commons::Exception); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ITimeUtilPtr TimeUtil(privateObject->getObject()); + std::string dateformat = TimeUtil->getTimeFormat(); + TimeUtilConverter converter(context); + + return converter.toJSValueRef(dateformat); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value");; + } Catch (UnsupportedException) { + LogError("JSTimeUtil::hasInstance NotSupportedException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::NOT_SUPPORTED_ERROR , "Not Support"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSTimeUtil::isLeapYear(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + Try { + TimeUtilPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + + if (argumentCount < 1) { + LogError("Wrong parameters"); + ThrowMsg(InvalidArgumentException, "Wrong parameters"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + long year = converter.FromJSValueReftolong(arguments[0]); + + if (year % 4 != 0) + return converter.toJSValueRef(false); + if (year % 400 == 0) + return converter.toJSValueRef(true); + if (year % 100 == 0) + return converter.toJSValueRef(false); + + return converter.toJSValueRef(true); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value");; + } Catch (UnsupportedException) { + LogError("JSTimeUtil::hasInstance NotSupportedException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::NOT_SUPPORTED_ERROR , "Not Support"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSTimeUtil::durationDifference(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LogDebug("Entered"); + Try { + TimeUtilPrivObject* privateObject = static_cast(JSObjectGetPrivate(thisObject)); + + if (argumentCount < 2) { + LogError("Wrong parameters"); + ThrowMsg(InvalidArgumentException, "Wrong parameters"); + } + + AceSecurityStatus status = TIMEUTIL_CHECK_ACCESS( + privateObject->getContext(), + TIMEUTIL_FUNCTION_API_READ_FUNCS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + TimeUtilConverter converter(context); + + DurationProperties first = converter.getDurationPropertis(arguments[0], exception); + DurationProperties second = converter.getDurationPropertis(arguments[1], exception); + + DurationProperties diff; + if (first.unit > second.unit) { + long long firstLength = converter.convertDurationLength(first, second.unit); + diff.unit = second.unit; + diff.length = firstLength - second.length; + } else { + long long secondLength = converter.convertDurationLength(second, first.unit); + diff.unit = first.unit; + diff.length = first.length - secondLength; + } + return converter.makeDurationObject(diff); + } Catch (InvalidArgumentException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::INVALID_VALUES_ERROR, "Invalid Value");; + } Catch (UnsupportedException) { + LogError("JSTimeUtil::hasInstance NotSupportedException"); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::NOT_SUPPORTED_ERROR , "Not Support"); + } Catch (PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } Catch (WrtDeviceApis::Commons::Exception) { + return JSTizenExceptionFactory::postException(context, exception, JSTizenException::UNKNOWN_ERROR, "Unknown Error"); + } + return JSValueMakeNull(context); +} + +} //Tizen1_0 +} //TizenApis diff --git a/src/standards/Tizen/TimeUtil/JSTimeUtil.h b/src/standards/Tizen/TimeUtil/JSTimeUtil.h new file mode 100755 index 0000000..8a2af29 --- /dev/null +++ b/src/standards/Tizen/TimeUtil/JSTimeUtil.h @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#ifndef WRT_PLUGINS_TIZEN_1_0_JS_TIMEUTIL_H_ +#define WRT_PLUGINS_TIZEN_1_0_JS_TIMEUTIL_H_ + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject TimeUtilPrivObject; + +/** + * @class JSTimeUtil + * @brief This class is javascript extension + * + */ +class JSTimeUtil +{ + public: + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + /** + * Gets class definition reference. + * @remarks New instance of JSClassRef is created (only once) if none was + * @remarks set before. + * @return Class reference. + */ + static const JSClassRef getClassRef(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef ctx, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception); + + /** + * Get current date/time. + */ + static JSValueRef getCurrentDateTime(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Set current date/time. + */ + static JSValueRef setCurrentDateTime(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Get local system timezone. + */ + static JSValueRef getLocalTimezone(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Get asynchronously the timezones supported by the system. + */ + static JSValueRef getAvailableTimezones(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getDateFormat(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getTimeFormat(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef isLeapYear(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + + static JSValueRef durationDifference(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function. + */ + static JSStaticFunction m_function[]; + + static JSClassRef m_jsClassRef; +}; +} +} + +#endif //WRT_PLUGINS_TIZEN_1_0_JS_TIMEUTIL_H_ \ No newline at end of file diff --git a/src/standards/Tizen/TimeUtil/TimeUtilConverter.cpp b/src/standards/Tizen/TimeUtil/TimeUtilConverter.cpp new file mode 100755 index 0000000..adf60ad --- /dev/null +++ b/src/standards/Tizen/TimeUtil/TimeUtilConverter.cpp @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#include +#include +#include +#include +#include +#include +#include + +#include "TimeUtilConverter.h" + +#include "JSTZDate.h" + +using namespace TizenApis::Api::TimeUtil; +using namespace WrtDeviceApis; + +namespace TizenApis { +namespace Tizen1_0 { + +TimeUtilConverter::TimeUtilConverter(JSContextRef context) +: WrtDeviceApis::CommonsJavaScript::Converter(context) { +} + +TimeUtilConverter::~TimeUtilConverter() { +} + +short TimeUtilConverter::toShort(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(tmp)); +} + +long TimeUtilConverter::FromJSValueReftolong(const JSValueRef& arg) { + if (!(JSValueIsNull(m_context, arg) || JSValueIsUndefined(m_context, arg)) + && (JSValueIsNumber(m_context, arg))) + return toLong(arg); + else + ThrowMsg(Commons::InvalidArgumentException, + "JSValueRef is JS null or JS undefined."); +} + +TZDateProperties TimeUtilConverter::getPropertiesInTZDate(JSValueRef arg) { + if (JSValueIsNull(m_context, arg) || JSValueIsUndefined(m_context, arg)) { + ThrowMsg(Commons::InvalidArgumentException, + "Message is JS null or JS undefined."); + } + JSObjectRef obj = toJSObjectRef(arg); + return getPropertiesInTZDate(obj); +} + + +TZDateProperties TimeUtilConverter::getPropertiesInTZDate(JSObjectRef arg) { + LogDebug("TZDate object=" << arg); + if (!arg) { + LogError("Object is null"); + ThrowMsg(Commons::NullPointerException, "Private object not initialized"); + } + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(arg)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(Commons::NullPointerException, "Private object not initialized"); + } + + ITZDatePtr TZDate = privateObject->getObject(); + TZDateProperties result; + + result.timezone = TZDate->getTimezone(); + result.year = TZDate->get(ITZDate::TZDATE_YEAR); + result.month = TZDate->get(ITZDate::TZDATE_MONTH); + result.day= TZDate->get(ITZDate::TZDATE_DATE); + result.hours= TZDate->get(ITZDate::TZDATE_HOUR_OF_DAY); + result.minutes= TZDate->get(ITZDate::TZDATE_MINUTE); + result.seconds= TZDate->get(ITZDate::TZDATE_SECOND); + result.milliseconds = TZDate->get(ITZDate::TZDATE_MILLISECOND); + return result; +} + +JSObjectRef TimeUtilConverter::makeDurationObject(const DurationProperties &duration) { + JSObjectRef propertyRef = JSObjectMake(m_context, NULL, NULL); + ScopedJSStringRef jsLengthString(JSStringCreateWithUTF8CString("length")); + ScopedJSStringRef jsUnitString(JSStringCreateWithUTF8CString("unit")); + std::string unitStr = "MSECS"; + switch (duration.unit) { + case DAYS_UNIT: + unitStr = "DAYS"; + break; + case SECONDS_UNIT: + unitStr = "SECS"; + break; + case MINUTES_UNIT: + unitStr = "MINS"; + break; + case HOURS_UNIT: + unitStr = "HOURS"; + break; + } + JSObjectSetProperty(m_context, propertyRef, jsLengthString.get(), toJSValueRef(static_cast(duration.length)), kJSPropertyAttributeNone, NULL); + JSObjectSetProperty(m_context, propertyRef, jsUnitString.get(), toJSValueRef(unitStr), kJSPropertyAttributeNone, NULL); + + return propertyRef; +} + +JSObjectRef TimeUtilConverter::makeMillisecondDurationObject(const long long length) { + DurationProperties duration; + duration.length = length; + duration.unit = MSECS_UNIT; + const long long dayToMsecs = 1000 * 60 * 60 * 24; + if ((length % dayToMsecs) == 0) { + duration.length = length / dayToMsecs; + duration.unit = DAYS_UNIT; + } + + return makeDurationObject(duration); +} + +DurationProperties TimeUtilConverter::getDurationPropertis(JSValueRef value, JSValueRef* exception) { + DurationProperties duration; + duration.length = getDurationLength(value, exception); + duration.unit = getDurationUnit(value, exception); + return duration; +} + +long long TimeUtilConverter::getDurationLength(JSValueRef value, JSValueRef* exception) { + JSValueRef l_JSProperty = JSUtils::getJSProperty(m_context, value, "length", exception); + double result = 0; + + if (l_JSProperty != NULL && JSValueIsNumber(m_context, l_JSProperty)) { + result = toDouble(l_JSProperty); + } else { + ThrowMsg(Commons::InvalidArgumentException, "Length doesn't exist or wrong type"); + } + return static_cast(result); +} + +short TimeUtilConverter::getDurationUnit(JSValueRef value, JSValueRef* exception) { + JSValueRef l_JSProperty = JSUtils::getJSProperty(m_context, value, "unit", exception); + std::string result = "MSECS"; + + if (l_JSProperty != NULL && JSValueIsString(m_context, l_JSProperty)) { + result = toString(l_JSProperty); + } + + if (!result.compare("DAYS")) + return DAYS_UNIT; + else if (!result.compare("SECS")) + return SECONDS_UNIT; + else if (!result.compare("MINS")) + return MINUTES_UNIT; + else if (!result.compare("HOURS")) + return HOURS_UNIT; + else + return MSECS_UNIT; + +} + +long long TimeUtilConverter::convertDurationLength(DurationProperties duration, short unit) { + if (duration.unit < unit) + ThrowMsg(Commons::ConversionException, "Unit is larger thatn duration's unit"); + + if (duration.unit == unit) + return duration.length; + + long long result = duration.length; + switch(unit) { + case MSECS_UNIT: + result = result * 1000; + if (duration.unit == SECONDS_UNIT) + return result; + case SECONDS_UNIT: + result = result * 60; + if (duration.unit == MINUTES_UNIT) + return result; + case MINUTES_UNIT: + result = result * 60; + if (duration.unit == HOURS_UNIT) + return result; + case HOURS_UNIT: + result = result * 24; + return result; + } +} + +std::time_t TimeUtilConverter::toTZDateTimeT(JSValueRef arg) { + if (JSValueIsNull(m_context, arg) || JSValueIsUndefined(m_context, arg)) { + ThrowMsg(Commons::InvalidArgumentException, + "JSValueRef is JS null or JS undefined."); + } + JSObjectRef obj = toJSObjectRef(arg); + + return toTZDateTimeT(obj); +} + +std::time_t TimeUtilConverter::toTZDateTimeT(JSObjectRef arg) { + if (!arg) { + LogError("Object is null"); + ThrowMsg(Commons::NullPointerException, "Private object not initialized"); + } + + TZDatePrivObject* privateObject = static_cast(JSObjectGetPrivate(arg)); + if (!privateObject) { + LogError("Private object is not set."); + ThrowMsg(Commons::NullPointerException, "Private object not initialized"); + } + + ITZDatePtr TZDate = privateObject->getObject(); + + TZDateProperties UTCProperties = TZDate->toLocalTimezone(); + struct tm localTm; + + localTm.tm_year = UTCProperties.year - 1900; + localTm.tm_mon = UTCProperties.month; + localTm.tm_mday= UTCProperties.day; + localTm.tm_hour= UTCProperties.hours; + localTm.tm_min=UTCProperties.minutes; + localTm.tm_sec= UTCProperties.seconds; + localTm.tm_isdst = 0; + + return mktime(&localTm); +} + +} +} diff --git a/src/standards/Tizen/TimeUtil/TimeUtilConverter.h b/src/standards/Tizen/TimeUtil/TimeUtilConverter.h new file mode 100755 index 0000000..e7fcd3a --- /dev/null +++ b/src/standards/Tizen/TimeUtil/TimeUtilConverter.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +#ifndef _JS_TIZEN10_TIMEUTIL_CONVERTER_H_ +#define _JS_TIZEN10_TIMEUTIL_CONVERTER_H_ + +#include +#include + +#include +#include + +#include +#include + +using namespace TizenApis::Api::TimeUtil; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace TizenApis { +namespace Tizen1_0 { + + +class TimeUtilConverter : public Converter +{ + public: + using Converter::toJSValueRef; + public: + explicit TimeUtilConverter(JSContextRef context); + virtual ~TimeUtilConverter(); + short toShort(const JSValueRef& arg); + long FromJSValueReftolong(const JSValueRef& arg); + + TZDateProperties getPropertiesInTZDate(JSValueRef arg); + TZDateProperties getPropertiesInTZDate(JSObjectRef arg); + JSObjectRef makeDurationObject(const DurationProperties &duration); + JSObjectRef makeMillisecondDurationObject(const long long length); + DurationProperties getDurationPropertis(JSValueRef value, JSValueRef* exception); + long long getDurationLength(JSValueRef value, JSValueRef* exception); + short getDurationUnit(JSValueRef value, JSValueRef* exception); + long long convertDurationLength(DurationProperties duration, short unit); + + std::time_t toTZDateTimeT(JSValueRef arg); + std::time_t toTZDateTimeT(JSObjectRef arg); + +}; + +typedef ConverterFactory TimeUtilConverterFactory; + +} +} + +#endif /* _JS_TIZEN10_TIMEUTIL_CONVERTER_H_ */ diff --git a/src/standards/Tizen/TimeUtil/config.xml b/src/standards/Tizen/TimeUtil/config.xml new file mode 100755 index 0000000..aaf4a68 --- /dev/null +++ b/src/standards/Tizen/TimeUtil/config.xml @@ -0,0 +1,26 @@ + + + + libwrt-plugins-tizen-1.0-time.so + time.install.uri + SAMSUNG plugin group + SAMSUNG certificate authority + AAAABBBBCCCCDDDEEEE0000 + + + http://tizen.org/api/time + time.read + time.write + + + + http://tizen.org/api/time.read + time.read + + + + http://tizen.org/api/time.write + time.write + + + diff --git a/src/standards/Tizen/TimeUtil/plugin_config.cpp b/src/standards/Tizen/TimeUtil/plugin_config.cpp new file mode 100755 index 0000000..add7fc8 --- /dev/null +++ b/src/standards/Tizen/TimeUtil/plugin_config.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#include +#include +#include +#include +#include + +#include "plugin_config.h" + +#define TIMEUTIL_FEATURE_API "http://tizen.org/api/time" +#define TIMEUTIL_FEATURE_API_READ "http://tizen.org/api/time.read" +#define TIMEUTIL_FEATURE_API_WRITE "http://tizen.org/api/time.write" + +#define TIMEUTIL_DEVICE_CAP_READ "time.read" +#define TIMEUTIL_DEVICE_CAP_WRITE "time.write" + +namespace TizenApis { +namespace Tizen1_0 { + +static WrtDeviceApis::Commons::FunctionMapping createTimeUtilFunctions(); + +static WrtDeviceApis::Commons::FunctionMapping TimeUtilFunctions = + createTimeUtilFunctions(); + +DEFINE_FUNCTION_GETTER(TimeUtil, TimeUtilFunctions); + +static WrtDeviceApis::Commons::FunctionMapping createTimeUtilFunctions() +{ + using namespace WrtDeviceApis::Commons; + + /** + * Device capabilities + */ + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_TIMEUTIL_READ, TIMEUTIL_DEVICE_CAP_READ); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_TIMEUTIL_WRITE, TIMEUTIL_DEVICE_CAP_WRITE); + + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_TIMEUTIL_READ); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_TIMEUTIL_READ, DEVICE_CAP_TIMEUTIL_READ); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_TIMEUTIL_WRITE); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_TIMEUTIL_WRITE, DEVICE_CAP_TIMEUTIL_WRITE); + + /** + * API features + */ + ACE_CREATE_FEATURE(FEATURE_TIMEUTIL, TIMEUTIL_FEATURE_API); + ACE_CREATE_FEATURE(FEATURE_READ, TIMEUTIL_FEATURE_API_READ); + ACE_CREATE_FEATURE(FEATURE_WRITE, TIMEUTIL_FEATURE_API_WRITE); + + + ACE_CREATE_FEATURE_LIST(TIMEUTIL_FEATURES_TIMEUTIL_READ); + ACE_ADD_API_FEATURE(TIMEUTIL_FEATURES_TIMEUTIL_READ, FEATURE_TIMEUTIL); + ACE_ADD_API_FEATURE(TIMEUTIL_FEATURES_TIMEUTIL_READ, FEATURE_READ); + + ACE_CREATE_FEATURE_LIST(TIMEUTIL_FEATURES_TIMEUTIL_WRITE); + ACE_ADD_API_FEATURE(TIMEUTIL_FEATURES_TIMEUTIL_WRITE, FEATURE_TIMEUTIL); + ACE_ADD_API_FEATURE(TIMEUTIL_FEATURES_TIMEUTIL_WRITE, FEATURE_WRITE); + + ACE_CREATE_FEATURE_LIST(TIMEUTIL_FEATURES_TIMEUTIL); + ACE_ADD_API_FEATURE(TIMEUTIL_FEATURES_TIMEUTIL, FEATURE_TIMEUTIL); + + ACE_CREATE_FEATURE_LIST(TIMEUTIL_FEATURES_READ); + ACE_ADD_API_FEATURE(TIMEUTIL_FEATURES_TIMEUTIL, FEATURE_READ); + + ACE_CREATE_FEATURE_LIST(TIMEUTIL_FEATURES_WRITE); + ACE_ADD_API_FEATURE(TIMEUTIL_FEATURES_TIMEUTIL, FEATURE_WRITE); + + /** + * Functions + */ + + FunctionMapping TimeUtilFunctions; + + AceFunction timeutilReadFuncs = ACE_CREATE_FUNCTION( + FUNCTION_TIMEUTIL_READ_FUNCTIONS, + TIMEUTIL_FUNCTION_API_READ_FUNCS, + TIMEUTIL_FEATURES_TIMEUTIL_READ, + DEVICE_LIST_TIMEUTIL_READ); + + TimeUtilFunctions.insert(std::make_pair( + TIMEUTIL_FUNCTION_API_READ_FUNCS, + timeutilReadFuncs)); + + AceFunction setCurrentDateTimeFunc = ACE_CREATE_FUNCTION( + FUNCTION_SET_CURRENT_DATETIME, + TIMEUTIL_FUNCTION_API_SET_CURRENT_DATE_TIME, + TIMEUTIL_FEATURES_TIMEUTIL_WRITE, + DEVICE_LIST_TIMEUTIL_WRITE); + + TimeUtilFunctions.insert(std::make_pair( + TIMEUTIL_FUNCTION_API_SET_CURRENT_DATE_TIME, + setCurrentDateTimeFunc)); + + return TimeUtilFunctions; +} +} // namespace Tizen1_0 +} // namespace TizenApis + +#undef TIMEUTIL_FEATURE_API +#undef TIMEUTIL_FEATURE_API_READ +#undef TIMEUTIL_FEATURE_API_WRITE +#undef TIMEUTIL_DEVICE_CAP_READ +#undef TIMEUTIL_DEVICE_CAP_WRITE diff --git a/src/standards/Tizen/TimeUtil/plugin_config.h b/src/standards/Tizen/TimeUtil/plugin_config.h new file mode 100755 index 0000000..3ac5265 --- /dev/null +++ b/src/standards/Tizen/TimeUtil/plugin_config.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _TIMEUTIL_PLUGIN_CONFIG_H_ +#define _TIMEUTIL_PLUGIN_CONFIG_H_ + +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +#define TIMEUTIL_FUNCTION_API_READ_FUNCS "TimeUtilReadFunctions" +#define TIMEUTIL_FUNCTION_API_SET_CURRENT_DATE_TIME "setCurrentDateTime" + +DECLARE_FUNCTION_GETTER(TimeUtil); + +#define TIMEUTIL_CHECK_ACCESS(globalContext, functionName) \ + aceCheckAccess >( \ + globalContext, \ + getTimeUtilFunctionData, \ + functionName) +} +} + +#endif // _TIMEUTIL_PLUGIN_CONFIG_H_ \ No newline at end of file diff --git a/src/standards/Tizen/TimeUtil/plugin_initializer.cpp b/src/standards/Tizen/TimeUtil/plugin_initializer.cpp new file mode 100755 index 0000000..ead733f --- /dev/null +++ b/src/standards/Tizen/TimeUtil/plugin_initializer.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include "JSTimeUtil.h" +#include "JSTZDate.h" + +void on_widget_start_callback(int widgetId, JavaScriptContext context, const engine_interface_t *interface) { + LogDebug("[TIZEN1.0\\TimeUtil] on_widget_start_callback ("< +#include +#include +#include "FilterConverter.h" + +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_TYPE "type" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_ORDER "order" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_FILTERS "filters" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_IDS "ids" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_ATTRIBUTE_NAME "attributeName" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_MATCH_FLAG "matchFlag" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_MATCH_VALUES "matchValues" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_CASE_SENSITIVE "caseSensitive" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_INITIAL_VALUE "initialValue" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_END_VALUE "endValue" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Tizen { + +using namespace TizenApis::Api::Tizen; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +using namespace std; + +FilterConverter::FilterConverter(JSContextRef context) : Converter(context) +{ + initFilterAttrs(); +} + +FilterConverter::~FilterConverter() +{ + LogDebug("entered"); +} + +MatchFlagArrayPtr FilterConverter::toMatchFlagArray(JSValueRef matchFlagArray) +{ + MatchFlagArrayPtr result; + Try { + result = MatchFlagArrayPtr(new MatchFlagArray(toVectorOfStrings(matchFlagArray))); + } Catch(ConversionException) { + ThrowMsg(InvalidArgumentException, "AttributeFilter.matchFlags has invalid type value."); + } + return result; +} + +JSValueRef FilterConverter::toJSValueRef(FilterPtr arg) +{ + JSValueRef result = NULL; + + if(arg->getFilterType() == UNION_FILTER || arg->getFilterType() == INTERSECTION_FILTER) + { + CompositeFilterPtr filter = DPL::DynamicPointerCast(arg); + + result = toJSValueRef(filter); + } + else if(arg->getFilterType() == ATTRIBUTE_FILTER) + { + AttributeFilterPtr filter = DPL::DynamicPointerCast(arg); + + result = toJSValueRef(filter); + } + else if(arg->getFilterType() == ATTRIBUTE_RANGE_FILTER) + { + AttributeRangeFilterPtr filter = DPL::DynamicPointerCast(arg); + + result = toJSValueRef(filter); + } + + return result; +} + +FilterPtr FilterConverter::toFilter(const JSValueRef& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "Filter is NULL."); + + if(!JSValueIsObject(m_context, arg)) + ThrowMsg(InvalidArgumentException, "Filter is not object."); + + JSObjectRef jsObject = toJSObjectRef(arg); + if(jsObject == NULL) + ThrowMsg(InvalidArgumentException, "Filter is not object."); + + BasicValidator validator = ValidatorFactory::getValidator(m_context); + + if(validator->checkArrayKeys(m_compositeFilterAttrs, arg)) + { + CompositeFilterPtr compositeFilter = toCompositeFilter(arg); + return DPL::StaticPointerCast(compositeFilter); + } + else if(validator->checkArrayKeys(m_attributeFilterAttrs, arg)) + { + AttributeFilterPtr attributeFilter = toAttributeFilter(arg); + return DPL::StaticPointerCast(attributeFilter); + } + else if(validator->checkArrayKeys(m_attributeRangeFilterAttrs, arg)) + { + AttributeRangeFilterPtr attributeRangeFilter = toAttributeRangeFilter(arg); + return DPL::StaticPointerCast(attributeRangeFilter); + } + + ThrowMsg(InvalidArgumentException, "Not a Filter."); + return FilterPtr(NULL); +} + +JSValueRef FilterConverter::toJSValueRef(const CompositeFilterPtr& arg) +{ + JSObjectRef resultObject = JSObjectMake(m_context, NULL, NULL); + + ScopedJSStringRef typeStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_TYPE)); + FilterType filterType = arg->getFilterType(); + string type; + if(filterType == UNION_FILTER) + type = "UNION"; + else if(filterType == INTERSECTION_FILTER) + type = "INTERSECTION"; + else + ThrowMsg(ConversionException, "Invalid FilterType."); + + ScopedJSStringRef typeValue(JSStringCreateWithUTF8CString(type.c_str())); + JSObjectSetProperty(m_context, resultObject, + typeStr.get(), + JSValueMakeString(m_context, typeValue.get()), + kJSPropertyAttributeNone, NULL); + + ScopedJSStringRef filtersStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_FILTERS)); + JSValueRef filters = toJSValueRef(arg->getFilters()); + JSObjectSetProperty(m_context, resultObject, + filtersStr.get(), + filters, + kJSPropertyAttributeNone, NULL); + + return static_cast(resultObject); +} + +CompositeFilterPtr FilterConverter::toCompositeFilter(const JSValueRef& arg) +{ + JSObjectRef jsObject = toJSObjectRef(arg); + + ScopedJSStringRef typeStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_TYPE)); + JSValueRef typeValue = JSObjectGetProperty(m_context, jsObject, typeStr.get(), NULL); + if(!JSValueIsString(m_context, typeValue)) + ThrowMsg(InvalidArgumentException, "CompositeFilter.type is not an string."); + string type = toString(typeValue); + FilterType filterType; + + if(type == "INTERSECTION") + filterType = INTERSECTION_FILTER; + else if(type == "UNION") + filterType = UNION_FILTER; + else + ThrowMsg(InvalidArgumentException, "CompositeFilter.type is wrong."); + + ScopedJSStringRef filtersStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_FILTERS)); + JSValueRef filtersValue = JSObjectGetProperty(m_context, jsObject, filtersStr.get(), NULL); + if(!JSIsArrayValue(m_context, filtersValue)) + ThrowMsg(InvalidArgumentException, "CompositeFilter.filters is not an array."); + FilterArrayPtr filters = toFilterArray(filtersValue); + if(filters->size() == 0) + ThrowMsg(InvalidArgumentException, "CompositeFilter.filters array size is 0."); + + return CompositeFilterPtr(new CompositeFilter(filterType, filters)); +} + +JSValueRef FilterConverter::toJSValueRef(const AttributeFilterPtr& arg) +{ + AnyTypeConverterFactory::ConverterType converter = + AnyTypeConverterFactory::getConverter(m_context); + + JSObjectRef resultObject = JSObjectMake(m_context, NULL, NULL); + + ScopedJSStringRef attributeNameStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_ATTRIBUTE_NAME)); + ScopedJSStringRef attributeNameValue(JSStringCreateWithUTF8CString(arg->getAttributeName().c_str())); + JSObjectSetProperty(m_context, resultObject, + attributeNameStr.get(), + JSValueMakeString(m_context, attributeNameValue.get()), + kJSPropertyAttributeNone, NULL); + + ScopedJSStringRef matchFlagStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_MATCH_FLAG)); + JSValueRef matchFlagValue = toJSValueRef(arg->getMatchFlag()); + JSObjectSetProperty(m_context, resultObject, + matchFlagStr.get(), + matchFlagValue, + kJSPropertyAttributeNone, NULL); + + ScopedJSStringRef matchValuesStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_MATCH_VALUES)); + JSValueRef matchValuesValue = toJSValueRef(arg->getMatchValues()); + JSObjectSetProperty(m_context, resultObject, + matchValuesStr.get(), + matchValuesValue, + kJSPropertyAttributeNone, NULL); + + ScopedJSStringRef caseSensitiveStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_CASE_SENSITIVE)); + JSValueRef caseSensitiveValue = converter->toJSValueRef(arg->getCaseSensitive()); + JSObjectSetProperty(m_context, resultObject, + caseSensitiveStr.get(), + caseSensitiveValue, + kJSPropertyAttributeNone, NULL); + + return static_cast(resultObject); +} + +AttributeFilterPtr FilterConverter::toAttributeFilter(const JSValueRef& arg) +{ + JSObjectRef jsObject = toJSObjectRef(arg); + + ScopedJSStringRef attributeNameStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_ATTRIBUTE_NAME)); + JSValueRef attributeNameValue = JSObjectGetProperty(m_context, jsObject, attributeNameStr.get(), NULL); + if(!JSValueIsString(m_context, attributeNameValue)) + ThrowMsg(InvalidArgumentException, "AttributeFilter.attributeName is not an string."); + string attributeName = toString(attributeNameValue); + if(attributeName == "") + ThrowMsg(InvalidArgumentException, "AttributeFilter.attributeName is empty string."); + + ScopedJSStringRef matchFlagStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_MATCH_FLAG)); + JSValueRef matchFlagValue = JSObjectGetProperty(m_context, jsObject, matchFlagStr.get(), NULL); + string matchFlag; + if(JSValueIsUndefined(m_context, matchFlagValue)) { + matchFlag = "EXACTLY"; + } else if(!JSValueIsString(m_context, matchFlagValue)) { + ThrowMsg(InvalidArgumentException, "AttributeFilter.matchFlag is not string."); + } else { + matchFlag = toString(matchFlagValue); + } + + ScopedJSStringRef matchValuesStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_MATCH_VALUES)); + JSValueRef matchValuesValue = JSObjectGetProperty(m_context, jsObject, matchValuesStr.get(), NULL); + AnyArrayPtr matchValues(NULL); + + if(matchFlag == "EXISTS") { + //matchValues = AnyArrayPtr(NULL); + } else if(JSValueIsUndefined(m_context, matchValuesValue)) { + ThrowMsg(InvalidArgumentException, "AttributeFilter.matchValues is undefined."); + } else if(!JSIsArrayValue(m_context, matchValuesValue)) { + ThrowMsg(InvalidArgumentException, "AttributeFilter.matchValues is not an array."); + } else { + matchValues = toAnyArray(matchValuesValue); + } + + ScopedJSStringRef caseSensitiveStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_CASE_SENSITIVE)); + JSValueRef caseSensitiveValue = JSObjectGetProperty(m_context, jsObject, caseSensitiveStr.get(), NULL); + bool caseSensitive; + if(JSValueIsUndefined(m_context, caseSensitiveValue)) { + if(matchFlag == "EXACTLY") + caseSensitive = true; + else + caseSensitive = false; + } else { + if(!JSValueIsBoolean(m_context, caseSensitiveValue)) { + ThrowMsg(InvalidArgumentException, "AttributeFilter.caseSensitive is not boolean."); + } + caseSensitive = toBool(caseSensitiveValue); + } + + return AttributeFilterPtr(new AttributeFilter(attributeName, matchValues, matchFlag, caseSensitive)); +} + +JSValueRef FilterConverter::toJSValueRef(const AttributeRangeFilterPtr& arg) +{ + AnyTypeConverterFactory::ConverterType converter = + AnyTypeConverterFactory::getConverter(m_context); + + JSObjectRef resultObject = JSObjectMake(m_context, NULL, NULL); + + ScopedJSStringRef attributeNameStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_ATTRIBUTE_NAME)); + ScopedJSStringRef attributeNameValue(JSStringCreateWithUTF8CString(arg->getAttributeName().c_str())); + JSObjectSetProperty(m_context, resultObject, + attributeNameStr.get(), + JSValueMakeString(m_context, attributeNameValue.get()), + kJSPropertyAttributeNone, NULL); + + ScopedJSStringRef initialValueStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_INITIAL_VALUE)); + JSValueRef initialValueValue = converter->toJSValueRef(arg->getInitialValue()); + JSObjectSetProperty(m_context, resultObject, + initialValueStr.get(), + initialValueValue, + kJSPropertyAttributeNone, NULL); + + ScopedJSStringRef endValueStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_END_VALUE)); + JSValueRef endValueValue = converter->toJSValueRef(arg->getEndValue()); + JSObjectSetProperty(m_context, resultObject, + endValueStr.get(), + endValueValue, + kJSPropertyAttributeNone, NULL); + + return static_cast(resultObject); +} + +AttributeRangeFilterPtr FilterConverter::toAttributeRangeFilter(const JSValueRef& arg) +{ + AnyTypeConverterFactory::ConverterType converter = + AnyTypeConverterFactory::getConverter(m_context); + + JSObjectRef jsObject = toJSObjectRef(arg); + + ScopedJSStringRef attributeNameStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_ATTRIBUTE_NAME)); + JSValueRef attributeNameValue = JSObjectGetProperty(m_context, jsObject, attributeNameStr.get(), NULL); + if(!JSValueIsString(m_context, attributeNameValue)) + ThrowMsg(InvalidArgumentException, "AttributeRangeFilter.attributeName is not an string."); + string attributeName = toString(attributeNameValue); + if(attributeName == "") + ThrowMsg(InvalidArgumentException, "AttributeRangeFilter.attributeName is empty string."); + + ScopedJSStringRef initialValueStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_INITIAL_VALUE)); + JSValueRef initialValueValue = JSObjectGetProperty(m_context, jsObject, initialValueStr.get(), NULL); + AnyPtr initialValue(NULL); + if(!JSValueIsUndefined(m_context, initialValueValue) && !JSValueIsNull(m_context, initialValueValue)) { + initialValue = converter->toAny(initialValueValue, PrimitiveType_Int); + } + + ScopedJSStringRef endValueStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_END_VALUE)); + JSValueRef endValueValue = JSObjectGetProperty(m_context, jsObject, endValueStr.get(), NULL); + AnyPtr endValue(NULL); + if(!JSValueIsUndefined(m_context, endValueValue) && !JSValueIsNull(m_context, endValueValue)) { + endValue = converter->toAny(endValueValue, PrimitiveType_Int); + } + + return AttributeRangeFilterPtr(new AttributeRangeFilter(attributeName, initialValue, endValue)); +} + +JSValueRef FilterConverter::toJSValueRef(const SortModePtr& arg) +{ + JSObjectRef resultObject = JSObjectMake(m_context, NULL, NULL); + + ScopedJSStringRef attributeNameStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_ATTRIBUTE_NAME)); + ScopedJSStringRef attributeNameValue(JSStringCreateWithUTF8CString(arg->getAttributeName().c_str())); + JSObjectSetProperty(m_context, resultObject, + attributeNameStr.get(), + JSValueMakeString(m_context, attributeNameValue.get()), + kJSPropertyAttributeNone, NULL); + + ScopedJSStringRef orderStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_ORDER)); + SortOrder sortOrder = arg->getOrder(); + string order; + if(sortOrder == ASCENDING_SORT_ORDER) + order = "ASC"; + else if(sortOrder == DESCENDING_SORT_ORDER) + order = "DESC"; + else + ThrowMsg(ConversionException, "Invalid SortMode."); + + ScopedJSStringRef orderValue(JSStringCreateWithUTF8CString(order.c_str())); + JSObjectSetProperty(m_context, resultObject, + orderStr.get(), + JSValueMakeString(m_context, orderValue.get()), + kJSPropertyAttributeNone, NULL); + + return static_cast(resultObject); +} + +SortModePtr FilterConverter::toSortMode(const JSValueRef& arg) +{ + BasicValidator validator = ValidatorFactory::getValidator(m_context); + + if(validator->checkArrayKeys(m_compositeFilterAttrs, arg)) { + ThrowMsg(InvalidArgumentException, "Not SortMode."); + } + + JSObjectRef jsObject = toJSObjectRef(arg); + + ScopedJSStringRef orderStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_ORDER)); + JSValueRef orderValue = JSObjectGetProperty(m_context, jsObject, orderStr.get(), NULL); + if(!JSValueIsString(m_context, orderValue)) + ThrowMsg(InvalidArgumentException, "SortMode.order is not an string."); + string order = toString(orderValue); + SortOrder sortOrder; + + if(order == "ASC") + sortOrder = ASCENDING_SORT_ORDER; + else if(order == "DESC") + sortOrder = DESCENDING_SORT_ORDER; + else + ThrowMsg(InvalidArgumentException, "SortMode.order is wrong."); + + ScopedJSStringRef attributeNameStr(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_ATTRIBUTE_NAME)); + JSValueRef attributeNameValue = JSObjectGetProperty(m_context, jsObject, attributeNameStr.get(), NULL); + if(!JSValueIsString(m_context, attributeNameValue)) + ThrowMsg(InvalidArgumentException, "SortMode.attributeName is not an string."); + string attributeName = toString(attributeNameValue); + if(attributeName == "") + ThrowMsg(InvalidArgumentException, "SortMode.attributeName is empty string."); + + return SortModePtr(new SortMode(attributeName, sortOrder)); +} + +JSValueRef FilterConverter::toJSValueRef(const SortModeArrayPtr& arg) +{ + int size = arg->size(); + + JSObjectRef resultObject = JSCreateArrayObject(m_context, 0, NULL); + if (!resultObject) + ThrowMsg(ConversionException, "Can not create array object."); + + for(int i = 0; i < size; i++) + { + JSValueRef jsvalue = toJSValueRef(arg->at(i)); + if (!JSSetArrayElement(m_context, resultObject, i, jsvalue)) + ThrowMsg(ConversionException, "Can not fill SortMode array."); + } + + return static_cast(resultObject); +} + +SortModeArrayPtr FilterConverter::toSortModeArray(const JSValueRef& arg) +{ + if(!JSIsArrayValue(m_context, arg)) + ThrowMsg(InvalidArgumentException, "Not an array type."); + + SortModeArrayPtr sortModeArray = SortModeArrayPtr(new SortModeArray()); + JSObjectRef object = toJSObjectRef(arg); + + unsigned int length = JSGetArrayLength(m_context, object); + for(unsigned int i=0; ipush_back(sortMode); + } + + return sortModeArray; +} + +JSValueRef FilterConverter::toJSValueRef(const AnyArrayPtr& arg) +{ + AnyTypeConverterFactory::ConverterType converter = + AnyTypeConverterFactory::getConverter(m_context); + + int size = arg->size(); + + JSObjectRef resultObject = JSCreateArrayObject(m_context, 0, NULL); + if (!resultObject) + ThrowMsg(ConversionException, "Can not create array object."); + + for(int i = 0; i < size; i++) + { + JSValueRef jsvalue = converter->toJSValueRef(arg->at(i)); + if (!JSSetArrayElement(m_context, resultObject, i, jsvalue)) + ThrowMsg(ConversionException, "Can not fill any array."); + } + + return static_cast(resultObject); +} + +AnyArrayPtr FilterConverter::toAnyArray(const JSValueRef& arg) +{ + AnyArrayPtr retVal; + + retVal = AnyArrayPtr(new AnyArray()); + + JSObjectRef obj = toJSObjectRef(arg); + AnyTypeConverterFactory::ConverterType converter = + AnyTypeConverterFactory::getConverter(m_context); + + unsigned int length = JSGetArrayLength(m_context, obj); + for(unsigned int i=0; itoAny(value, PrimitiveType_Int); + + retVal->push_back(any); + } + + return retVal; +} + +JSValueRef FilterConverter::toJSValueRef(const FilterArrayPtr& arg) +{ + int size = arg->size(); + + JSObjectRef resultObject = JSCreateArrayObject(m_context, 0, NULL); + if (!resultObject) + ThrowMsg(ConversionException, "Can not create array object."); + + for(int i = 0; i < size; i++) + { + JSValueRef jsvalue = toJSValueRef(arg->at(i)); + if (!JSSetArrayElement(m_context, resultObject, i, jsvalue)) + ThrowMsg(ConversionException, "Can not fill filter array."); + } + + return static_cast(resultObject); +} + +FilterArrayPtr FilterConverter::toFilterArray(const JSValueRef& arg) +{ + FilterArrayPtr retVal; + + JSObjectRef obj = toJSObjectRef(arg); + retVal = FilterArrayPtr(new FilterArray()); + + unsigned int length = JSGetArrayLength(m_context, obj); + for(unsigned int i=0; ipush_back(filter); + } + + return retVal; +} + +void FilterConverter::initFilterAttrs() +{ + m_compositeFilterAttrs.push_back(TIZEN_FILTER_CONVERTER_ATTRIBUTE_TYPE); + m_compositeFilterAttrs.push_back(TIZEN_FILTER_CONVERTER_ATTRIBUTE_FILTERS); + + m_attributeFilterAttrs.push_back(TIZEN_FILTER_CONVERTER_ATTRIBUTE_ATTRIBUTE_NAME); + m_attributeFilterAttrs.push_back(TIZEN_FILTER_CONVERTER_ATTRIBUTE_MATCH_FLAG); + m_attributeFilterAttrs.push_back(TIZEN_FILTER_CONVERTER_ATTRIBUTE_MATCH_VALUES); + m_attributeFilterAttrs.push_back(TIZEN_FILTER_CONVERTER_ATTRIBUTE_CASE_SENSITIVE); + + m_attributeRangeFilterAttrs.push_back(TIZEN_FILTER_CONVERTER_ATTRIBUTE_ATTRIBUTE_NAME); + m_attributeRangeFilterAttrs.push_back(TIZEN_FILTER_CONVERTER_ATTRIBUTE_INITIAL_VALUE); + m_attributeRangeFilterAttrs.push_back(TIZEN_FILTER_CONVERTER_ATTRIBUTE_END_VALUE); + + m_sortModeAttrs.push_back(TIZEN_FILTER_CONVERTER_ATTRIBUTE_ORDER); + m_sortModeAttrs.push_back(TIZEN_FILTER_CONVERTER_ATTRIBUTE_ATTRIBUTE_NAME); +} + +} // Tizen +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Tizen/FilterConverter.h b/src/standards/Tizen/Tizen/FilterConverter.h new file mode 100755 index 0000000..9d9f675 --- /dev/null +++ b/src/standards/Tizen/Tizen/FilterConverter.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file FilterConverter.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @description Reference from CalendarConverter.h + */ + +#ifndef _TIZEN_FILTER_CONVERTER_H_ +#define _TIZEN_FILTER_CONVERTER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Tizen { + +class FilterConverter : public WrtDeviceApis::CommonsJavaScript::Converter +{ +public: + using WrtDeviceApis::CommonsJavaScript::Converter::toJSValueRef; +public: + explicit FilterConverter(JSContextRef context); + virtual ~FilterConverter(); + + TizenApis::Api::Tizen::MatchFlagArrayPtr toMatchFlagArray(JSValueRef matchFlagArray); + + JSValueRef toJSValueRef(TizenApis::Api::Tizen::FilterPtr arg); + TizenApis::Api::Tizen::FilterPtr toFilter(const JSValueRef& arg); + + JSValueRef toJSValueRef(const TizenApis::Api::Tizen::CompositeFilterPtr& arg); + TizenApis::Api::Tizen::CompositeFilterPtr toCompositeFilter(const JSValueRef& arg); + + JSValueRef toJSValueRef(const TizenApis::Api::Tizen::AttributeFilterPtr& arg); + TizenApis::Api::Tizen::AttributeFilterPtr toAttributeFilter(const JSValueRef& arg); + + JSValueRef toJSValueRef(const TizenApis::Api::Tizen::AttributeRangeFilterPtr& arg); + TizenApis::Api::Tizen::AttributeRangeFilterPtr toAttributeRangeFilter(const JSValueRef& arg); + + JSValueRef toJSValueRef(const TizenApis::Api::Tizen::SortModePtr& arg); + TizenApis::Api::Tizen::SortModePtr toSortMode(const JSValueRef& arg); + + JSValueRef toJSValueRef(const TizenApis::Api::Tizen::SortModeArrayPtr& arg); + TizenApis::Api::Tizen::SortModeArrayPtr toSortModeArray(const JSValueRef& arg); + + JSValueRef toJSValueRef(const TizenApis::Api::Tizen::AnyArrayPtr& arg); + TizenApis::Api::Tizen::AnyArrayPtr toAnyArray(const JSValueRef& arg); + + JSValueRef toJSValueRef(const TizenApis::Api::Tizen::FilterArrayPtr& arg); + TizenApis::Api::Tizen::FilterArrayPtr toFilterArray(const JSValueRef& arg); + +private: + std::vector m_compositeFilterAttrs; + std::vector m_attributeFilterAttrs; + std::vector m_attributeRangeFilterAttrs; + std::vector m_sortModeAttrs; + + void initFilterAttrs(); +}; + +typedef WrtDeviceApis::CommonsJavaScript::ConverterFactory FilterConverterFactory; + +} // Tizen +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_FILTER_CONVERTER_H_ diff --git a/src/standards/Tizen/Tizen/JSFeature.cpp b/src/standards/Tizen/Tizen/JSFeature.cpp new file mode 100755 index 0000000..fae6337 --- /dev/null +++ b/src/standards/Tizen/Tizen/JSFeature.cpp @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSFeature.cpp + * @author + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include "JSFeature.h" +#include "JSFeatureParam.h" + + +namespace TizenApis { +namespace Tizen1_0 { +namespace Tizen { + +namespace { + const char* PLUGIN_NAME = "Feature"; + const char* ATTRIBUTE_URI = "uri"; + const char* ATTRIBUTE_REQUIRED = "required"; + const char* ATTRIBUTE_PARAMS = "params"; +} + +JSClassDefinition JSFeature::m_classInfo = +{ + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + m_properties, + NULL, //m_functions, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, //hasInstance, + NULL //convertToType +}; + +JSStaticValue JSFeature::m_properties[] = { + { ATTRIBUTE_URI, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { ATTRIBUTE_REQUIRED, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { ATTRIBUTE_PARAMS, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassDefinition* JSFeature::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSFeature::m_classRef = JSClassCreate(JSFeature::getClassInfo()); + +void JSFeature::initialize(JSContextRef context, JSObjectRef object) +{ + //LogDebug("entered"); + //private object should be passed to JSObjectMake function. + //Nothing to do here. +} + +void JSFeature::finalize(JSObjectRef object) +{ + LogDebug("entered"); + JSFeaturePrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; +} + +JSClassRef JSFeature::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSFeature::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("entered"); + JSFeaturePrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + LogError("no private object"); + return JSValueMakeUndefined(context); + } + Try + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + if (JSStringIsEqualToUTF8CString(propertyName, ATTRIBUTE_URI)) { + return converter.toJSValueRef(priv->getObject()->getName() ); + } + else if (JSStringIsEqualToUTF8CString(propertyName, ATTRIBUTE_REQUIRED)) { + if (priv->getObject()->isRequestedByWidget()) { + return converter.toJSValueRef(priv->getObject()->isRequired() ); + } + return JSValueMakeNull(context); + } + else if (JSStringIsEqualToUTF8CString(propertyName, ATTRIBUTE_PARAMS)) { + if (priv->getObject()->isRequestedByWidget()) { + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + if (jsResult) { + WrtDeviceApis::Commons::IWidgetFeature::Params params = priv->getObject()->getParams(); + WrtDeviceApis::Commons::IWidgetFeature::ParamsIterator it = params.begin(); + size_t i = 0; + for (; it != params.end(); ++it, ++i) { + std::pair param = make_pair(it->first, it->second); + JSFeatureParamPrivObject *priv = new JSFeatureParamPrivObject(context, param); + JSObjectRef tempVal = JSObjectMake(context, JSFeatureParam::getClassRef(), priv); + JSSetArrayElement(context, jsResult, i, tempVal); + } + return jsResult; + } + } + return JSValueMakeNull(context); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error during conversion"); + } + return JSValueMakeUndefined(context); +} + +} // Tizen +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Tizen/JSFeature.h b/src/standards/Tizen/Tizen/JSFeature.h new file mode 100755 index 0000000..5afa8a5 --- /dev/null +++ b/src/standards/Tizen/Tizen/JSFeature.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSFeature.h + * @author + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_FEATURE_H_ +#define _WRT_PLUGIN_JS_FEATURE_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Tizen { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject JSFeaturePrivateObject; + +/** + * @class JSFeature + * @brief This class is javascript extenstion + * + */ +class JSFeature +{ +public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_properties[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_classRef; + +}; + +} // Tizen +} // Tizen1_0 +} // TizenApis + +#endif // _WRT_PLUGIN_JS_FEATURE_H_ diff --git a/src/standards/Tizen/Tizen/JSFeatureParam.cpp b/src/standards/Tizen/Tizen/JSFeatureParam.cpp new file mode 100755 index 0000000..fb4f54c --- /dev/null +++ b/src/standards/Tizen/Tizen/JSFeatureParam.cpp @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSFeatureParam.cpp + * @author + * @version 0.1 + * @brief + */ + +#include +#include +#include "JSFeatureParam.h" + + +namespace TizenApis { +namespace Tizen1_0 { +namespace Tizen { + +namespace { + const char* PLUGIN_NAME = "Param"; + const char* ATTRIBUTE_NAME = "name"; + const char* ATTRIBUTE_VALUE = "value"; +} + +JSClassDefinition JSFeatureParam::m_classInfo = +{ + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + m_properties, + NULL, //m_functions, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, //hasInstance, + NULL //convertToType +}; + +JSStaticValue JSFeatureParam::m_properties[] = { + { ATTRIBUTE_NAME, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { ATTRIBUTE_VALUE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassDefinition* JSFeatureParam::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSFeatureParam::m_classRef = JSClassCreate(JSFeatureParam::getClassInfo()); + + +void JSFeatureParam::initialize(JSContextRef context, JSObjectRef object) +{ + LogDebug("entered"); + //private object should be passed to JSObjectMake function. + //Nothing to do here. +} + +void JSFeatureParam::finalize(JSObjectRef object) +{ + LogDebug("entered"); + JSFeatureParamPrivObject* priv = + static_cast(JSObjectGetPrivate(object)); + delete priv; +} + +JSClassRef JSFeatureParam::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSFeatureParam::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("entered"); + JSFeatureParamPrivObject* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv) { + LogError("no private object"); + return JSValueMakeUndefined(context); + } + Try + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + std::string propertyNameStr = converter.toString(propertyName); + if (propertyNameStr == ATTRIBUTE_NAME) { + return converter.toJSValueRef(priv->getObject().first); + } + else if (propertyNameStr == ATTRIBUTE_VALUE) { + return converter.toJSValueRef(priv->getObject().second); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("error during conversion"); + } + return JSValueMakeUndefined(context); +} + +} // Tizen +} // Tizen1_0 +} // TizenApis diff --git a/src/standards/Tizen/Tizen/JSFeatureParam.h b/src/standards/Tizen/Tizen/JSFeatureParam.h new file mode 100755 index 0000000..602dea1 --- /dev/null +++ b/src/standards/Tizen/Tizen/JSFeatureParam.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSFeatureParam.h + * @author + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_FEATURE_PARAM_H_ +#define _WRT_PLUGIN_JS_FEATURE_PARAM_H_ + +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Tizen { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSFeatureParamPrivObject; + +/** + * @class JSFeatureParam + * @brief This class is javascript extenstion + * + */ +class JSFeatureParam +{ +public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_properties[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_classRef; + +}; + +} // Tizen +} // Tizen1_0 +} // TizenApis + +#endif // _WRT_PLUGIN_JS_FEATURE_PARAM_H_ diff --git a/src/standards/Tizen/Tizen/JSTizen.cpp b/src/standards/Tizen/Tizen/JSTizen.cpp new file mode 100755 index 0000000..ad92400 --- /dev/null +++ b/src/standards/Tizen/Tizen/JSTizen.cpp @@ -0,0 +1,380 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file JSTizen.cpp + * @author + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "JSTizen.h" +#include "JSFeature.h" +#include "plugin_config.h" + +#include + +#define PLUGIN_NAME "tizen" +#define FUNCTION_LIST_AVAILABLE_FEATURES "listAvailableFeatures" +#define FUNCTION_LIST_ACTIVATED_FEATURES "listActivatedFeatures" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Tizen { + +using namespace WrtDeviceApis::Commons; +using namespace TizenApis::Api::Tizen; + +JSClassDefinition JSTizen::m_classInfo = +{ + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + m_properties, + m_functions, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + deleteProperty, + getPropertyNames, + NULL, + NULL, + hasInstance, + convertToType +}; + +JSStaticValue JSTizen::m_properties[] = { + { 0, 0, 0 } +}; + +JSStaticFunction JSTizen::m_functions[] = { + { FUNCTION_LIST_AVAILABLE_FEATURES, listAvailableFeatures, kJSPropertyAttributeNone}, + { FUNCTION_LIST_ACTIVATED_FEATURES, listActivatedFeatures, kJSPropertyAttributeNone}, + { 0, 0, 0 } +}; + +const JSClassDefinition* JSTizen::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSTizen::m_classRef = JSClassCreate(JSTizen::getClassInfo()); + +void JSTizen::initialize(JSContextRef context, JSObjectRef object) +{ + LogDebug("entered"); + TizenPrivate* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + if (priv) { + delete priv; + } + IWrtWrapperPtr wrapper; + Try + { + wrapper = WrtWrappersMgr::getInstance().getWrtWrapper(context); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) + { + LogError("Cannot get WRT wrapper."); + LogError("You should register your wrapper in ON_WIDGET_START"); + return; + } + + PluginOnDemandPrivPtr privObject(new PluginOnDemandPriv(wrapper)); + + priv = new TizenPrivate(context, privObject); + if (!JSObjectSetPrivate(object, static_cast(priv))) { + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +void JSTizen::finalize(JSObjectRef object) +{ + LogDebug("entered"); + TizenPrivate* priv = static_cast(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + +JSClassRef JSTizen::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +bool JSTizen::deleteProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + return true; +} + +void JSTizen::getPropertyNames(JSContextRef context, JSObjectRef object, + JSPropertyNameAccumulatorRef propertyNames) +{ +} + +bool JSTizen::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) +{ + return true; +} + +JSValueRef JSTizen::convertToType(JSContextRef context, JSObjectRef object, + JSType type, JSValueRef* exception) +{ + return JSValueMakeUndefined(context); +} + +bool JSTizen::hasProperty(JSContextRef context, + JSObjectRef object, JSStringRef propertyName) +{ + LogDebug("entered"); + + Try + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + std::string propName = converter.toString(propertyName); + LogDebug("checking property:" + propName); + + TizenPrivate* priv = static_cast(JSObjectGetPrivate(object)); + + if (!priv || !priv->getObject()) { + LogError("No private obejct"); + return false; + } + PluginOnDemandPrivPtr privObj = priv->getObject(); + PluginOnDemandPriv::ObjectListPtr objList = privObj->getObjectList(); + + if (objList->find(propName) != objList->end()) { + //already set so property exists + return true; + } + + std::string pluginUri(PLUGIN_NAME); + pluginUri.append(".").append(propName); + if (privObj->getWrtWrapper()->isJSObjectAvailable(pluginUri)) { + LogDebug(propName + " is available"); + //property can be set + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("Error occured"); + } + + //let JSCore to handle this property + return false; +} + +JSValueRef JSTizen::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + std::string propName = converter.toString(propertyName); + + TizenPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv || !priv->getObject()) { + LogError("No private obejct"); + return false; + } + PluginOnDemandPrivPtr privObj = priv->getObject(); + PluginOnDemandPriv::ObjectListPtr objList = privObj->getObjectList(); + + PluginOnDemandPriv::ObjectList::iterator it = objList->find(propName); + if (it != objList->end()) { + //return already set value + return it->second; + } + + std::string pluginUri(PLUGIN_NAME); + pluginUri.append(".").append(propName); + LogDebug("load new object : " << pluginUri); + //load new plugin + privObj->setAllowSettingProperty(true); + privObj->getWrtWrapper()->loadJSObject(pluginUri); + privObj->setAllowSettingProperty(false); + it = objList->find(propName); + if (it != objList->end()) { + //return value + return it->second; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("Error occured"); + } + + /* During normal operation flow should not reach here, + but wrt may fail with loading plugin. */ + return JSValueMakeUndefined(context); +} + +bool JSTizen::setProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + LogDebug("entered"); + Try + { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + std::string propName = converter.toString(propertyName); + + TizenPrivate* priv = + static_cast(JSObjectGetPrivate(object)); + if (!priv || !priv->getObject()) { + LogError("No private obejct"); + return false; + } + PluginOnDemandPrivPtr privObj = priv->getObject(); + + std::string pluginUri(PLUGIN_NAME); + pluginUri.append(".").append(propName); + if (privObj->getAllowSettingProperty()) { + JSValueProtect(priv->getContext(), value); + (*privObj->getObjectList())[propName] = value; + return true; + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LogError("Error occured"); + } + + //this code should not be reached. setProperty is not called when + //hasProperty returns false. Anyway, if we didn't set value then we + //return false. + return false; +} + +JSValueRef JSTizen::listAvailableFeatures(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception) +{ + LogDebug("entered"); + IWrtWrapperPtr wrapper; + + TizenPrivate* priv = static_cast(JSObjectGetPrivate(thisObject)); + assert(priv); + + /* + * Current Tizen spec assures that tizen is always available + AccessStatus status = DEVICEAPIS_CHECK_ACCESS(priv->getContext(), + DEVICEAPIS_FUNCTION_API_LIST_AVAIL_FEATURES); + + SYNC_ACCESS_STATUS_HANDLER(status, context, exception); + */ + + try + { + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "No private object"); + } +// wrapper = priv->getObject(); + PluginOnDemandPrivPtr privObj = priv->getObject(); + wrapper = privObj->getWrtWrapper(); + } + catch(const WrtDeviceApis::Commons::Exception &ex) + { + LogError("couldn't get wrapper, " << ex.GetMessage()); + return WrtDeviceApis::CommonsJavaScript::JSDOMExceptionFactory::UnknownException.make(context, exception); + } + JSObjectRef result = JSCreateArrayObject(context, 0, NULL); + IWrtWrapper::Features features = wrapper->getRegisteredFeatures(); + for (size_t i=0; i(JSObjectGetPrivate(thisObject)); + assert(priv); + + /* + * Current Tizen spec assures that tizen is always available + AccessStatus status = DEVICEAPIS_CHECK_ACCESS(priv->getContext(), + DEVICEAPIS_FUNCTION_API_LIST_ACTIV_FEATURES); + + SYNC_ACCESS_STATUS_HANDLER(status, context, exception);*/ + IWrtWrapperPtr wrapper; + try + { + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "No private object"); + } + PluginOnDemandPrivPtr privObj = priv->getObject(); + wrapper = privObj->getWrtWrapper(); + } + catch(const WrtDeviceApis::Commons::Exception &ex) + { + LogError("couldn't get wrapper, " << ex.GetMessage()); + return WrtDeviceApis::CommonsJavaScript::JSDOMExceptionFactory::UnknownException.make(context, exception); + } + JSObjectRef result = JSCreateArrayObject(context, 0, NULL); + IWrtWrapper::Features features = wrapper->getWidgetFeatures(); + for (size_t i=0; i +#include +#include "PluginOnDemandPriv.h" + + +namespace TizenApis { +namespace Tizen1_0 { +namespace Tizen { + +/** + * @class JSBondi + * @brief This class is javascript extenstion + * + */ + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT::Type TizenPrivate; + + +class JSTizen { +public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when determining whether an object has a property. + */ + static bool hasProperty(JSContextRef context, + JSObjectRef object, JSStringRef propertyName); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + /** + * The callback invoked when setting a property's value. + */ + static bool setProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef value, JSValueRef* exception); + + /** + * The callback invoked when deleting a property. + */ + static bool deleteProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + /** + * The callback invoked when collecting the names of an object's properties. + */ + static void getPropertyNames(JSContextRef ctx, JSObjectRef object, + JSPropertyNameAccumulatorRef propertyNames); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef ctx, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception); + + /** + * The callback invoked when converting an object to a particular JavaScript type. + */ + static JSValueRef convertToType(JSContextRef ctx, JSObjectRef object, + JSType type, JSValueRef* exception); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_properties[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function. + */ + static JSStaticFunction m_functions[]; + + static JSClassRef m_classRef; + + static JSValueRef listAvailableFeatures(JSContextRef context, + JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef listActivatedFeatures(JSContextRef context, + JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); +}; + +} // Tizen +} // Tizen1_0 +} // TizenApis + +#endif // _WRT_PLUGIN_JS_XXX_H_ diff --git a/src/standards/Tizen/Tizen/PluginOnDemandPriv.cpp b/src/standards/Tizen/Tizen/PluginOnDemandPriv.cpp new file mode 100755 index 0000000..3418116 --- /dev/null +++ b/src/standards/Tizen/Tizen/PluginOnDemandPriv.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file PluginOnDemandPriv.cpp + * @author + * @version 0.1 + * @brief + */ + +#include "PluginOnDemandPriv.h" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Tizen { + +PluginOnDemandPriv::PluginOnDemandPriv(const WrtDeviceApis::Commons::IWrtWrapperPtr &wrapper) : + m_objectList(new ObjectList()), + m_wrtWrapper(wrapper), + m_allowSettingProperty(false) +{ +} + +PluginOnDemandPriv::~PluginOnDemandPriv() +{ +} + +WrtDeviceApis::Commons::IWrtWrapperPtr PluginOnDemandPriv::getWrtWrapper() const +{ + return m_wrtWrapper; +} + +PluginOnDemandPriv::ObjectListPtr PluginOnDemandPriv::getObjectList() const +{ + return m_objectList; +} + +bool PluginOnDemandPriv::getAllowSettingProperty() const +{ + return m_allowSettingProperty; +} + +void PluginOnDemandPriv::setAllowSettingProperty(bool allowSettingProperty) +{ + m_allowSettingProperty = allowSettingProperty; +} + +} +} +} diff --git a/src/standards/Tizen/Tizen/PluginOnDemandPriv.h b/src/standards/Tizen/Tizen/PluginOnDemandPriv.h new file mode 100755 index 0000000..72620c9 --- /dev/null +++ b/src/standards/Tizen/Tizen/PluginOnDemandPriv.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file PluginOnDemandPriv.h + * @author + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_STANDARDS_TIZEN_DEVICEAPIS_PLUGIN_ON_DEMAND_PRIV +#define _WRT_PLUGIN_STANDARDS_TIZEN_DEVICEAPIS_PLUGIN_ON_DEMAND_PRIV + +#include +#include +#include +#include +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Tizen { + +class PluginOnDemandPriv +{ + public: + + typedef std::map ObjectList; + typedef DPL::SharedPtr ObjectListPtr; + + explicit PluginOnDemandPriv(const WrtDeviceApis::Commons::IWrtWrapperPtr &wrapper); + virtual ~PluginOnDemandPriv(); + WrtDeviceApis::Commons::IWrtWrapperPtr getWrtWrapper() const; + ObjectListPtr getObjectList() const; + bool getAllowSettingProperty() const; + void setAllowSettingProperty(bool allowSettingProperty); + + private: + ObjectListPtr m_objectList; + WrtDeviceApis::Commons::IWrtWrapperPtr m_wrtWrapper; + bool m_allowSettingProperty; +}; + +typedef DPL::SharedPtr PluginOnDemandPrivPtr; + +} +} +} + +#endif diff --git a/src/standards/Tizen/Tizen/config.xml b/src/standards/Tizen/Tizen/config.xml new file mode 100755 index 0000000..ebb372e --- /dev/null +++ b/src/standards/Tizen/Tizen/config.xml @@ -0,0 +1,25 @@ + + + + libwrt-plugins-tizen-1.0-tizen.so + tizen.install.uri + SAMSUNG plugin group + SAMSUNG certificate authority + AAAABBBBCCCCDDDEEEE0000 + + + http://tizen.org/api/tizen + + + + + + diff --git a/src/standards/Tizen/Tizen/plugin_config.cpp b/src/standards/Tizen/Tizen/plugin_config.cpp new file mode 100755 index 0000000..1f51128 --- /dev/null +++ b/src/standards/Tizen/Tizen/plugin_config.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file plugin_config.cpp + * @author + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include + +#define TIZEN_FEATURE_API "http://tizen.org/api/tizen" + +namespace TizenApis { +namespace Tizen1_0 { +namespace Tizen { + +const char* TIZEN_FUNCTION_API_LIST_AVAIL_FEATURES = + "listAvailableFeatures"; +const char* TIZEN_FUNCTION_API_LIST_ACTIV_FEATURES = + "listActivatedFeatures"; + +static WrtDeviceApis::Commons::FunctionMapping createDeviceApisFunctions(); + +static WrtDeviceApis::Commons::FunctionMapping DeviceApisFunctions = + createDeviceApisFunctions(); + +DEFINE_FUNCTION_GETTER(DeviceApis, DeviceApisFunctions); + +static WrtDeviceApis::Commons::FunctionMapping createDeviceApisFunctions() +{ + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + // + // --- features ---- + // + + ACE_CREATE_FEATURE(FEATURE_TIZEN,TIZEN_FEATURE_API); + + ACE_CREATE_FEATURE_LIST(FEATURE_LIST_TIZEN); + ACE_ADD_API_FEATURE(FEATURE_LIST_TIZEN,FEATURE_TIZEN); + + // + // --- functions --- + // + + WrtDeviceApis::Commons::FunctionMapping DeviceApisMapping; + + //LIST_AVAIL + WrtDeviceApis::Commons::AceFunction listAvailableFeaturesFuncs = ACE_CREATE_FUNCTION( + FUNCTION_LIST_AVAILABLE_FEATURES, + TIZEN_FUNCTION_API_LIST_AVAIL_FEATURES, + FEATURE_LIST_TIZEN, + EMPTY_DEVICE_LIST); + + DeviceApisMapping.insert( + std::make_pair( + TIZEN_FUNCTION_API_LIST_AVAIL_FEATURES, + listAvailableFeaturesFuncs)); + + //LIST_ACTIV + WrtDeviceApis::Commons::AceFunction listActivatedFeaturesFunc = ACE_CREATE_FUNCTION( + FUNCTION_LIST_ACTIVATED_FEATURES, + TIZEN_FUNCTION_API_LIST_ACTIV_FEATURES, + FEATURE_LIST_TIZEN, + EMPTY_DEVICE_LIST); + + DeviceApisMapping.insert( + std::make_pair( + TIZEN_FUNCTION_API_LIST_ACTIV_FEATURES, + listActivatedFeaturesFunc)); + + return DeviceApisMapping; +} + +} +} // namespace Tizen1_0 +} // namespace TizenApis + +#undef TIZEN_FEATURE_API +#undef TIZEN_FUNCTION_API_LIST_ACTIV_FEATURES +#undef TIZEN_FUNCTION_API_LIST_AVAIL_FEATURES diff --git a/src/standards/Tizen/Tizen/plugin_config.h b/src/standards/Tizen/Tizen/plugin_config.h new file mode 100755 index 0000000..fff9fc0 --- /dev/null +++ b/src/standards/Tizen/Tizen/plugin_config.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file plugin_config.h + * @author + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_PLUGIN_CONFIG_H_ +#define _TIZEN_PLUGIN_CONFIG_H_ + +#include + +namespace TizenApis { +namespace Tizen1_0 { +namespace Tizen { + +extern const char* TIZEN_FUNCTION_API_LIST_AVAIL_FEATURES; +extern const char* TIZEN_FUNCTION_API_LIST_ACTIV_FEATURES; +extern const char* TIZEN_FUNCTION_API_CREATE_COMPOSITE_FILTER; +extern const char* TIZEN_FUNCTION_API_CREATE_ATTRIBUTE_FILTER; +extern const char* TIZEN_FUNCTION_API_CREATE_ATTRIBUTE_RANGE_FILTER; +extern const char* TIZEN_FUNCTION_API_CREATE_ID_FILTER; +extern const char* TIZEN_FUNCTION_API_CREATE_SORT_MODE; + +} +} +} + +#endif // _TIZEN_PLUGIN_CONFIG_H_ diff --git a/src/standards/Tizen/Tizen/plugin_initializer.cpp b/src/standards/Tizen/Tizen/plugin_initializer.cpp new file mode 100755 index 0000000..99873c5 --- /dev/null +++ b/src/standards/Tizen/Tizen/plugin_initializer.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file plugin_initializer.cpp + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include "JSTizen.h" + +#define WRT_JS_EXTENSION_OBJECT_TIZEN "tizen" + +#define OBJECT_TIZEN "tizen" + +void on_widget_start_callback(int widgetId, JavaScriptContext context, const engine_interface_t *interface) +{ + LogDebug("[Tizen\\xxx] on_widget_start_callback ("<